php поменять местами ключи и значения массива

array_flip

(PHP 4, PHP 5, PHP 7, PHP 8)

array_flip — Меняет местами ключи с их значениями в массиве

Описание

Функция array_flip() возвращает массив ( array ) наоборот, то есть ключи массива array становятся значениями, а значения массива array становятся ключами.

Если значение встречается несколько раз, для обработки будет использоваться последний встреченный ключ, а все остальные будут потеряны.

Список параметров

Массив переворачиваемых пар ключ/значение.

Возвращаемые значения

Возвращает перевёрнутый массив в случае успешного выполнения и null в случае возникновения ошибки.

Примеры

Пример #1 Пример использования array_flip()

Результат выполнения данного примера:

Пример #2 Пример использования array_flip() с коллизиями

Результат выполнения данного примера:

Смотрите также

User Contributed Notes 18 notes

This function is useful when parsing a CSV file with a heading column, but the columns might vary in order or presence:

?>

I find this better than referencing the numerical array index.

array_flip will remove duplicate values in the original array when you flip either an associative or numeric array. As you might expect it’s the earlier of two duplicates that is lost:

array(3) <
[0] => string(3) «one»
[1] => string(3) «two»
[2] => string(3) «one»
>

This may be good or bad, depending on what you want, but no error is thrown.

array_flip() does not retain the data type of values, when converting them into keys. 🙁

It is valid expectation that string values «1», «2» and «3» would become string keys «1», «2» and «3».

When you do array_flip, it takes the last key accurence for each value, but be aware that keys order in flipped array will be in the order, values were first seen in original array. For example, array:

In my application I needed to find five most recently commented entries. I had a sorted comment-id => entry-id array, and what popped in my mind is just do array_flip($array), and I thought I now would have last five entries in the array as most recently commented entry => comment pairs. In fact it wasn’t (see above, as it is the order of values used). To achieve what I need I came up with the following (in case someone will need to do something like that):

First, we need a way to flip an array, taking the first encountered key for each of values in array. You can do it with:

Well, and to achieve that «last comments» effect, just do:

$array = array_reverse($array, true);
$array = array_flip(array_unique($array));
$array = array_reverse($array, true);

In the example from the very beginning array will become:

Just what I (and maybe you?) need. =^_^=

In case anyone is wondering how array_flip() treats empty arrays:

( array_flip (array()));
?>

results in:

I wanted to know if it would return false and/or even chuck out an error if there were no key-value pairs to flip, despite being non-intuitive if that were the case. But (of course) everything works as expected. Just a head’s up for the paranoid.

I needed a way to flip a multidimensional array and came up with this function to accomplish the task. I hope it helps someone else.

Источник

Функции для работы с массивами

Содержание

User Contributed Notes 14 notes

A simple trick that can help you to guess what diff/intersect or sort function does by name.

Example: array_diff_assoc, array_intersect_assoc.

Example: array_diff_key, array_intersect_key.

Example: array_diff, array_intersect.

Example: array_udiff_uassoc, array_uintersect_assoc.

This also works with array sort functions:

Example: arsort, asort.

Example: uksort, ksort.

Example: rsort, krsort.

Example: usort, uasort.

?>
Return:
Array ( [ 0 ] => Cero [ 1 ] => Uno [ 2 ] => Dos [ 3 ] => Cuatro [ 4 ] => Cinco [ 5 ] => Tres [ 6 ] => Seis [ 7 ] => Siete [ 8 ] => Ocho [ 9 ] => Nueve [ 10 ] => Diez )
Array ( [ 0 ] => Cero [ 1 ] => Uno [ 2 ] => Dos [ 3 ] => Tres [ 4 ] => Cuatro [ 5 ] => Cinco [ 6 ] => Seis [ 7 ] => Siete [ 8 ] => Ocho [ 9 ] => Nueve [ 10 ] => Diez )
?>

Updated code of ‘indioeuropeo’ with option to input string-based keys.

Here is a function to find out the maximum depth of a multidimensional array.

// return depth of given array
// if Array is a string ArrayDepth() will return 0
// usage: int ArrayDepth(array Array)

Short function for making a recursive array copy while cloning objects on the way.

If you need to flattern two-dismensional array with single values assoc subarrays, you could use this function:

to 2g4wx3:
i think better way for this is using JSON, if you have such module in your PHP. See json.org.

to convert JS array to JSON string: arr.toJSONString();
to convert JSON string to PHP array: json_decode($jsonString);

You can also stringify objects, numbers, etc.

Function to pretty print arrays and objects. Detects object recursion and allows setting a maximum depth. Based on arraytostring and u_print_r from the print_r function notes. Should be called like so:

I was looking for an array aggregation function here and ended up writing this one.

Note: This implementation assumes that none of the fields you’re aggregating on contain The ‘@’ symbol.

While PHP has well over three-score array functions, array_rotate is strangely missing as of PHP 5.3. Searching online offered several solutions, but the ones I found have defects such as inefficiently looping through the array or ignoring keys.

Источник

Php поменять местами ключи и значения массива

Меняет местами индексы и значения массива.
Синтаксис:

Эта функция «пробегает» по массиву и меняет местами его ключи и значения. Исходный массив arr не изменяется, а результирующий массив просто возвращается. Если в массиве присутствовало несколько элементов с одинаковыми значениями, учитываться будет только последний из них.

Значения массива arr должны быть либо целыми числами, либо строковыми значениями. Иначе пара ключ / значение не будут обработаны.

Функция array_flip() возвратит FALSE, если обработка массива вызвала ошибку.

Пример использования функции array_flip():

Пример использования функции array_flip():

Приведенный выше пример выведет следующее:

Функция поддерживается PHP 4, PHP 5

Функция устанавливает значения ключей массива в верхний или нижний регистр.
Синтаксис:

Пример выведет следующее:

Функция поддерживается PHP 4 >= 4.2.0, PHP 5

Пример выведет следующее:

Функция поддерживается PHP 5

Проверка существования заданного ключа в массиве.
Синтаксис:

Функция array_key_exists() возвратит TRUE, если в массиве search присутствует элемент с индексом key.
В противном случае возвратит FALSE.

Пример использования функции array_key_exists():

В PHP 4.0.6. имя этой функции key_exists().

Функция поддерживается PHP 4 >= 4.0.1, PHP 5

Вычислить произведение значений массива (PHP 5 >= 5.1.0RC1)

array_product() возвращает произведение значений массива как целое число или число с плавающей точкой.

Пример использования array_product()

Результат выполнения данного примера:

Итеративно уменьшить массив к единственному значению, используя функцию обратного вызова (PHP 4 >= 4.0.5, PHP 5)

array_reduce() итеративно применяет функцию function к элементам массива input и, таким образом, сводит массив к единственному значению. Если указан дополнительный параметр initial, он будет использован в начале процесса, или в качестве окончательного результата, если массив пуст.

Рекурсивно применить пользовательскую функцию к каждому элементу массива (PHP 5)

Применяет пользовательскую функцию funcname к каждому элементу массива input. Эта функция обрабатывает каждый элемент многомерного массива. Обычно у функции funcname два параметра. Значение массива array в качестве первого параметра, и ключ/индекс в качестве второго. Если указан дополнительный параметр userdata, он будет передан в качестве третьего параметра в функцию обратного вызова funcname.

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Замечание: Если требуется, чтобы функция funcname изменила значения в массиве, определите первый параметр funcname как ссылку. Тогда все изменения будут применены к элементам массива.

Пример использования array_walk_recursive()

Вывод вышеприведённой программы:

Обратите внимание, что ключ ‘sweet’ никогда не отображается. Никакой ключ, соответствующий значению типа array, не будет передан в функцию.

Возвращает список из ключей массива.
Синтаксис:

Функция возвращает массив, значениями которого являются все строковые и числовые ключи массива arr. Если задан необязательный параметр search_value, то она вернет только те ключи, которым соответствуют значению search_value.
Пример испольльзования функции array_keys():

Приведенный выше пример выведет следующее:

Функция array_keys() появилась в PHP 4.

Ее эквивалент для PHP 3:

Функция поддерживается PHP 4, PHP 5

Удаление ассоциативных индексов массива.
Синтаксис:

Функция array_values() возвращает список всех значений в ассоциативном массиве arr. При этом она заменяет все строковые ключи на числовые.
Пример использования функции array_values():

Этот пример выведет:

Функция поддерживается PHP 4, PHP 5

Осуществляет проверку массива на наличие значения.
Синтаксис:

Функция in_array() возвратит TRUE, если в массиве haystack содержится элемент со значением needle, и FALSE в противном случае.
Если установить третий необязательный параметр strict в значение TRUE, то функция in_array() при проверке также будет сравнивать типы значений.
Замечание: Если параметр needle является строкой, то при сравнении регистр символов учитывается.
Замечание: В PHP версии ниже 4.2.0 параметр needle не мог быть массивом.
Пример использования функции in_array():

Второе условие не сработает, т.к. поиск в массиве идет с учетом регистра.
Пример выведет:

Пример использования функции in_array(): Использование параметра strict

Функция поддерживается PHP 4, PHP 5

Возвращает количество значений массива.
Синтаксис:

Пример выведет следующее:

Функция поддерживается PHP 4, PHP 5

Возвращает число элементов массива.
Синтаксис:

Функция sizeof() возвращает количество элементов в массиве arr на подобие действия функции count().

Возвращает число элементов в массиве или объекте.
Синтаксис:

Если задан необязательный параметр mode, то будет подсчитано общее количество элементов в массиве. Это может быть полезно при нахождении количества элементов в многомерных массивах.
Пример использования функции count():

Пример использования функции count(): (PHP >= 4.2.0)

Функция поддерживается PHP 3, PHP 4, PHP 5

Возвращает сумму всех элементов массива.
Синтаксис:

Функция array_sum() возвращает сумму всех числовых элементов массива. От типа значений в массиве зависит тип возвращаемого числа (integer или float).

Пример использования функции array_sum():

Этот пример выведет следующее:

Функция поддерживается PHP 4 >=4.0.4, PHP 5

Производит случайную выборку индексов массива.
Синтаксис:

Функция array_rand() будет полезной, если вы хотите выбрать одно или несколько случайных значений из массива. Эта функция возвращает в массиве выбранные случайным образом индексы элементов массива arr.
Аргумент num_req указывает число возвращаемых индексов. В случае, если выбирается один элемент, то функция array_rand() возвратит случайный ключ в виде значения.
Пример использования функции array_rand():

Источник

array_walk

(PHP 4, PHP 5, PHP 7, PHP 8)

array_walk — Применяет заданную пользователем функцию к каждому элементу массива

Описание

Список параметров

Если требуется, чтобы функция callback изменила значения в массиве, определите первый параметр callback как ссылку. Тогда все изменения будут применены к элементам оригинального массива.

Потенциально изменены могут быть только значения массива array ; структура самого массива не может быть изменена, то есть нельзя добавить, удалить или поменять порядок элементов. Если callback-функция не соответствует этому требованию, поведение данной функции станет неопределённым и непредсказуемым.

Возвращаемые значения

Возвращает true

Ошибки

Примеры

Пример #1 Пример использования array_walk()

Результат выполнения данного примера:

Смотрите также

User Contributed Notes 34 notes

PHP ignored arguments type when using array_walk() even if there was

declare( strict_types = 1 );

butter: 5
meat: 7
banana: 3

whilst the expecting output is :

Fatal error: Uncaught TypeError: Argument 1 passed to test_print() must be of the type integer

because «butter» => 5.3 is float

I asked someone about it and they said «this was caused by the fact that callbacks called from internal code will always use weak type». But I tried to do some tests and this behavior is not an issue when using call_user_func().

Calling an array Walk inside a class

If the class is static:
array_walk($array, array(‘self’, ‘walkFunction’));
or
array_walk($array, array(‘className’, ‘walkFunction’));

Otherwise:
array_walk($array, array($this, ‘walkFunction’));

There is a note about 3 years ago regarding using this for trimming. array_map() may be cleaner for this. I haven’t checked the time/resource impact:

Correction for the speed test from zlobnygrif.

// Test results
$array1 = test ( ‘array_walk’ );
$array2 = test ( ‘array_walk_list_each’ );
$array3 = test ( ‘array_walk_foreach1’ );
$array4 = test ( ‘array_walk_foreach2’ );

In response to ‘ibolmo’, this is an extended version of string_walk, allowing to pass userdata (like array_walk) and to have the function edit the string in the same manner as array_walk allows, note now though that you have to pass a variable, since PHP cannot pass string literals by reference (logically).

// We can make that with this simple FOREACH loop :

$fruits = array(«d» => «lemon», «a» => «orange», «b» => «banana», «c» => «apple»);

Array
(
[d] => fruit: lemon
[a] => fruit: orange
[b] => fruit: banana
[c] => fruit: apple
)

For those that think they can’t use array_walk to change / replace a key name, here you go:

I wanted to walk an array and reverse map it into a second array. I decided to use array_walk because it should be faster than a reset,next loop or foreach(x as &$y) loop.

Don’t forget about the array_map() function, it may be easier to use!

Here’s how to lower-case all elements in an array:

It can be very useful to pass the third (optional) parameter by reference while modifying it permanently in callback function. This will cause passing modified parameter to next iteration of array_walk(). The exaple below enumerates items in the array:

Array
(
[0] => 1 lemon
[1] => 2 orange
[2] => 3 banana
[3] => 4 apple
)
$num is: 1

As a conclusion, using references with array_walk() can be powerful toy but this should be done carefully since modifying third parameter outside the array_walk() is not always what we want.

array_walk does not work on SplFixedArray objects:
= new SplFixedArray ( 2 );
$array [ 0 ] = ‘test_1’ ;
$array [ 1 ] = ‘test_2’ ;

Unfortunately I spent a lot of time trying to permanently apply the effects of a function to an array using the array_walk function when instead array_map was what I wanted. Here is a very simple though effective example for those who may be getting overly frustrated with this function.

Prefix array values with keys and retrieve as a glued string, the original array remains unchanged. I used this to create some SQL queries from arrays.

Using lambdas you can create a handy zip function to zip together the keys and values of an array. I extended it to allow you to pass in the «glue» string as the optional userdata parameter. The following example is used to zip an array of email headers:

/*
From: Matthew Purdon
Reply-To: Matthew Purdon
Return-path:
X-Mailer: PHP5.3.2
Content-Type: text/plain; charset=»UTF-8″
*/
?>

// Test results
$array1 = test ( ‘array_walk’ );
$array2 = test ( ‘array_walk_list_each’ );
$array3 = test ( ‘array_walk_foreach1’ );
$array4 = test ( ‘array_walk_foreach2’ );

PHP 5.5 array_walk looks pretty good but list each is more and more quickly.

For completeness one has to mention the possibility of using this function with PHP 5.3 closures:

You can use lambda function as a second parameter:

I was looking for trimming all the elements in an array, I found this as the simplest solution:

And to set allow_call_time_pass_reference to true in php.ini won’t work, according to http://bugs.php.net/bug.php?id=19699 thus to work around:

example with closures, checking and deleting value in array:

You can change the key or value with array_walk if you use the temporal returned array in global inside the function. For example:

$array = [‘a’=>10, ‘b’=>20];
$sequence = array ();

$newArray = array_values(array_walk($array, ‘fn’));

No need to concern about the place of the internal pointer for the baby array. You have now rewinded, 0 based new array, string key one instead.

If you want to add values with same key from two arrays :

echo «» ;
?>

This will output:

«orange» => 3,
«banana» => 3,
«apple» => 5

here is a simple and yet easy to use implementation of this function.
the ‘original’ function has the problem that you can’t unset a value.
with my function, YOU CAN!

limitations: it only can run user defined functions.
i hope you like it!

You want to get rid of the whitespaces users add in your form fields.
Simply use.

so.
$obj = new SomeVeryImportantClass;
$obj->mungeFormData($_POST);
___
eNc

For all those people trying to shoe-horn trim() into array_walk() and have found all these tricks to work around the issue with array_walk() passing 2 parameters to the callback.

Check out array_map().

It’s all sorts of win.

For the record. I’m one of these people and after 15 years of php development I’m pleased to say that there’s still things I’m learning. 🙂 I just found out about array_map() myself.

return true ; // success!
> // arrayWalk()

So, still some work left.

Beware that «array ($this, method)» construct. If you’re wanting to alter members of the «$this» object inside «method» you should construct the callback like this:

if you want to modify every value of an multidimensional array use this function used here:

Array ( [ 1 ] => 1test [ 2 ] => 2test [ 3 ] => Array ( [ 1 ] => 11test [ 2 ] => 12test [ 3 ] => 13test ) )
?>

Источник

array_replace_recursive

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

array_replace_recursive — Рекурсивно заменяет элементы первого массива элементами переданных массивов

Описание

array_replace_recursive() заменяет значения массива array на соответствующие по ключам значения из всех следующих массивов. Если ключ из первого массива есть во втором, его значение будет заменено на значение из второго массива. Если ключ есть во втором массиве, но отсутствует в первом, он будет создан в первом массиве. Если ключ есть только в первом массиве, то он остаётся как есть. Если передано несколько массивов, они будут обработаны по порядку, последующие перезаписывают предыдущие значения.

Список параметров

Массив, элементы которого будут заменены.

Массивы, из которых будут браться элементы для замены.

Возвращаемые значения

Примеры

Пример #1 Пример использования array_replace_recursive()

Результат выполнения данного примера:

Пример #2 array_replace_recursive() и рекурсивное поведение

Результат выполнения данного примера:

Смотрите также

User Contributed Notes 7 notes

(I suppose it treats it as just another recursive level to dive in, finding no key to compare, backtracking while leaving this sub-tree alone)

$result is still: [‘first’ => [‘second’ => ‘hello’]].

Nice that this function finally found its was to the PHP core! If you want to use it also with older PHP versions before 5.3.0, you can define it this way:

If you implemented such a compatible function before and don’t want to refactor all your code, you can update it with the following snippet to use the native (and hopefully faster) implementation of PHP 5.3.0, if available. Just start your function with these lines:

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *