Php array walk this

What is array_walk

The array_walk applies a callback function to every member of an array.

Function Signature

array_walk(array|object &$array, callable $callback, mixed $arg = null): bool

Arguments

  • array – The input array
  • callback – A function that applies to every member of an array (See notes below)
  • arg – If this argument is supplied, then it is passed as a third parameter to the callback function

Notes

  • The callback takes two arguments: value and the key corresponding to the keys and values of the array.
  • If arg is supplied, then that is passed as a third argument to the callback function.
  • If the callback is supposed to modify the input array values, the value parameter must be passed through reference.
  • The values of the input array could be changed only. Any attempt to change the input array structure by adding, removing or reordering elements will make the function unpredictable.

Return Type

Returns true

Errors/Exceptions

As of PHP 7.1.0, the function throws ArgumentCountError if more than two arguments are required for the callback. In previous versions, the function generated E_WARNING in a similar case.

Introduction

PHP array_walk function sounds similar to array_walk_recursive that we have seen before. The fundamental difference is obvious from their names. The array_walk_recursive, as the name suggests, recursively applies a callback function to a multidimensional array. That’s why array_walk_recursive is the right pick if we have to work with a multidimensional array. However, there were few caveats about the function that we have seen before.

Читайте также:  Html select name size

The array_walk function is different because it doesn’t recurse deep into arrays but works with top-level array elements. Thus it is a convenient way to apply a user-defined function to an array using this function. We can use built-in functions too, but that requires programmers to go an extra mile and define wrappers, as we will see in this article.

So, let’s move on to examples to get familiar with this function and learn important caveats of this function.

array_walk

array_walk : Usage Example#1

We have an array of integers, and we want to multiply all of these integers by two. One way is to define a foreach loop and loop through the array. However, the PHP array walk simplifies the code and does it in a one-liner. Thus keeping the code clean and efficient. Let’s see how.

); print_r($integers); /* OUTPUT Array ( [0] => -2000000 [1] => -200000 [2] => -20000 [3] => -2000 [4] => -200 [5] => -20 [6] => 0 [7] => 20 [8] => 200 [9] => 2000 [10] => 20000 [11] => 200000 [12] => 2000000 ) */ ?> 

Quite convenient. Have you noticed the & before the first argument in the callback array. That indicates to PHP that the value is passed by reference. If we don’t pass this parameter by reference, the change won’t reflect in the integers array.

array_walk : Usage Example#2

Sometimes we may want to pass a built-in PHP function to the PHP array walk. However, that’s usually not possible because a built-in function signature may not match what array_walk expects in the callback.

To understand this, we take an example of the PHP strtolower function. This function takes a string and makes it lowercase. The function signature is as follows.

strtolower(string $string): string

Now think for a while, can we pass this function directly as a callback to array_walk? Certainly not because callback expects two arguments fundamentally, as we have seen.

So, what’s the way out. The way out is to use wrapper functions. See the example below.

//Wrapper function for strtolower function wrapper_strtolower(&$value,$key,$arg=null)

Observe that the wrapper function’s signature matches the expected callback function signature, accepting two arguments value and key while the third arg argument is optional.

Let’s use that as a callback function in the PHP array walk.

$languages = ["PHP","JAVA","JAVASCRIPT","PYTHON","GO","RUBY","PERL"]; array_walk($languages,'wrapper_strtolower'); print_r($languages); /* OUTPUT Array ( [0] => php [1] => java [2] => javascript [3] => python [4] => go [5] => ruby [6] => perl ) */ 

Voila! It works just perfectly. The wrapper function is a downside because we have to make a wrapper function for every built-on function. The good news is that we have a solution for that too. Let’s find this out in the next usage example.

array_walk : Usage Example#3

So we are looking for an efficient way to avoid defining wrappers for built-in functions because it becomes impractical to keep on defining wrappers for virtually every function we want to use in the callback. Instead, we define a wrapper for the array_walk function and make it adaptable for almost every function.
The following example is a wrapped array_walk function.

//A wrapper function for array_walk function wrapper_arraywalk_referential(&$array,$function,$parameters=array()) < $reference_function = function(&$value, $key, $userdata) < $parameters = array_merge(array($value), $userdata[1]); $value = call_user_func_array($userdata[0], $parameters); >; array_walk_recursive($array, $reference_function, array($function, $parameters)); > 

Let’s use the wrapped PHP array walk in a practical scenario.

Superb. We have just used the array_walk wrapper function with PHP strip_tags function, applying it to all the HTML elements in the array. We don’t have to define a wrapper for the strip_tags function. So, you can use the wrapper function to call any built-in PHP function or user-defined functions.

Conclusion

This article explains the array_walk function in PHP. We’ve seen several important caveats about the function. If the function is supposed to modify the input array elements, the callback must take the first parameter by reference. Moreover, we have seen wrapper function and used a clever approach by defining a wrapper for the PHP array walk instead of defining wrapper functions for every function we intend to call, which is inefficient and redundant.

That’s it for this article. We hope you’ve enjoyed it. Stay tuned for more interesting and exciting PHP articles.

Stephen Miracle

Stephen Miracle

Hey! I hope you enjoyed this article. I have been professionally developing websites & software for well over 20 years. I started FuelingPHP as a way to give back to the open-source community that helped me be able to live comfortably building things I love.

Источник

array_walk

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

array_walk() не подвержена влиянию внутреннего указателя массива array . array_walk() обойдёт все элементы массива независимо от позиции указателя.

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

Обычно функция callback принимает два параметра. В качестве первого параметра идет значение элемента массива array , а ключ — в качестве второго.

Замечание:

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

Замечание:

Множество встроенных функций (например, strtolower() ) выводят предупреждение, если им передано больше параметров, чем они ожидают, или которые не могут непосредственно использоваться в callback .

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

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

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

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

Ошибки

Если функция callback требует больше параметров, чем передано на самом деле, каждый раз, когда array_walk() будет вызывать callback , будет генерироваться ошибка уровня E_WARNING.

Примеры

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

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

function test_print ( $item2 , $key )
echo » $key . $item2
\n» ;
>

echo «До . \n» ;
array_walk ( $fruits , ‘test_print’ );

array_walk ( $fruits , ‘test_alter’ , ‘fruit’ );
echo «. и после:\n» ;

array_walk ( $fruits , ‘test_print’ );
?>

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

До . d. lemon a. orange b. banana c. apple . и после: d. fruit: lemon a. fruit: orange b. fruit: banana c. fruit: apple

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

  • array_walk_recursive() — Рекурсивно применяет пользовательскую функцию к каждому элементу массива
  • iterator_apply() — Вызывает функцию для каждого элемента в итераторе
  • list() — Присваивает переменным из списка значения подобно массиву
  • each() — Возвращает текущую пару ключ/значение из массива и смещает его указатель
  • call_user_func_array() — Вызывает пользовательскую функцию с массивом параметров
  • array_map() — Применяет callback-функцию ко всем элементам указанных массивов
  • информация о типе callback
  • foreach

Источник

array_walk

Applies the user-defined callback function to each element of the array array.

array_walk() is not affected by the internal array pointer of array . array_walk() will walk through the entire array regardless of pointer position.

Parameters

Typically, callback takes on two parameters. The array parameter’s value being the first, and the key/index second.

Note:

If callback needs to be working with the actual values of the array, specify the first parameter of callback as a reference. Then, any changes made to those elements will be made in the original array itself.

Note:

Many internal functions (for example strtolower() ) will throw a warning if more than the expected number of argument are passed in and are not usable directly as a callback .

Only the values of the array may potentially be changed; its structure cannot be altered, i.e., the programmer cannot add, unset or reorder elements. If the callback does not respect this requirement, the behavior of this function is undefined, and unpredictable.

If the optional arg parameter is supplied, it will be passed as the third parameter to the callback .

Return Values

Returns true .

Errors/Exceptions

As of PHP 7.1.0, an ArgumentCountError will be thrown if the callback function requires more than 2 parameters (the value and key of the array member), or more than 3 parameters if the arg is also passed. Previously, in this case an error of level E_WARNING would be generated each time array_walk() calls callback .

Changelog

Version Description
8.0.0 If callback expects the second or third parameter to be passed by reference, this function will now emit an E_WARNING .

Examples

Example #1 array_walk() example

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

function test_print ( $item2 , $key )
echo » $key . $item2 \n» ;
>

echo «Before . \n» ;
array_walk ( $fruits , ‘test_print’ );

array_walk ( $fruits , ‘test_alter’ , ‘fruit’ );
echo «. and after:\n» ;

array_walk ( $fruits , ‘test_print’ );
?>

The above example will output:

Before . d. lemon a. orange b. banana c. apple . and after: d. fruit: lemon a. fruit: orange b. fruit: banana c. fruit: apple

Example #2 array_walk() example using anonymous function

array_walk ( $elements , function ( $value , $key ) echo » < $key >=> < $value >\n» ;
>);

The above example will output:

See Also

  • array_walk_recursive() — Apply a user function recursively to every member of an array
  • iterator_apply() — Call a function for every element in an iterator
  • list() — Assign variables as if they were an array
  • each() — Return the current key and value pair from an array and advance the array cursor
  • call_user_func_array() — Call a callback with an array of parameters
  • array_map() — Applies the callback to the elements of the given arrays
  • foreach
  • Array Functions
    • array_​change_​key_​case
    • array_​chunk
    • array_​column
    • array_​combine
    • array_​count_​values
    • array_​diff_​assoc
    • array_​diff_​key
    • array_​diff_​uassoc
    • array_​diff_​ukey
    • array_​diff
    • array_​fill_​keys
    • array_​fill
    • array_​filter
    • array_​flip
    • array_​intersect_​assoc
    • array_​intersect_​key
    • array_​intersect_​uassoc
    • array_​intersect_​ukey
    • array_​intersect
    • array_​is_​list
    • array_​key_​exists
    • array_​key_​first
    • array_​key_​last
    • array_​keys
    • array_​map
    • array_​merge_​recursive
    • array_​merge
    • array_​multisort
    • array_​pad
    • array_​pop
    • array_​product
    • array_​push
    • array_​rand
    • array_​reduce
    • array_​replace_​recursive
    • array_​replace
    • array_​reverse
    • array_​search
    • array_​shift
    • array_​slice
    • array_​splice
    • array_​sum
    • array_​udiff_​assoc
    • array_​udiff_​uassoc
    • array_​udiff
    • array_​uintersect_​assoc
    • array_​uintersect_​uassoc
    • array_​uintersect
    • array_​unique
    • array_​unshift
    • array_​values
    • array_​walk_​recursive
    • array_​walk
    • array
    • arsort
    • asort
    • compact
    • count
    • current
    • end
    • extract
    • in_​array
    • key_​exists
    • key
    • krsort
    • ksort
    • list
    • natcasesort
    • natsort
    • next
    • pos
    • prev
    • range
    • reset
    • rsort
    • shuffle
    • sizeof
    • sort
    • uasort
    • uksort
    • usort
    • each

    Источник

Оцените статью