Array walk function in php

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.

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.

Читайте также:  Java is ascii letter

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.

Читайте также:  Python datetime создать дату

Источник

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

Источник

PHP Array_Walk With Advanced Example

php array_walk

In this tutorial, we will learn about PHP Array_Walk with advanced example programs.

By the end of this tutorial, you’ll have a better understanding of what array _walk in PHP does with example programs. Before we begin, if you missed any of our prior lessons, you can review the topics in our PHP Tutorial for Beginners.

Definition and Usage

PHP has a built-in function called array_walk() which calls a user-defined function for each element in an array. The function needs to know the keys and values of the array.

This goes through an entire array, no matter where the pointer is, and applies the callback function or a user-defined function to each element. The internal array pointer of the array doesn’t change how the array_walk() function works.

Syntax

array_walk( array, myfunction, parameter )

Parameters

Technical Details

Errors/Exceptions

Since PHP 7.1.0, an ArgumentCountError is triggered if a callback function requires more than two parameters (the value and key of the array member) or more than three parameters if the arg is also given. Previously, an error of level E_WARNING would be generated each time array_walk() called callback in this circumstance.

Читайте также:  Php class sql select

Example of array_walk()

By using a parameter:

"; > $array_sample = array( "A" => "Apple", "B" => "Banana", "C" => "Cucumber" ); array_walk( $array_sample, "myfunction", "is equal to" ); ?>
A is equal to Apple B is equal to Banana C is equal to Cucumber

The three arguments to the myfunction function are $value , $key , and $p . With these arguments, you can print the array values, the keys that go with them, and a short description.

The $array_sample variable is used to declare an array with specific keys and values.

Finally, an array_walk is used to call the user-defined function and display it in an array.

Change an array element’s value in array walk PHP

With the array_walk() function, we can change all of the elements in the array. We need to send the &$value , not just the $value . Notice the & difference.

"); function myfunction( &$value, $key ) < $value = "Mango"; >$array_sample = array( "A" => "Apple", "B" => "Banana", "C" => "Cucumber" ); array_walk( $array_sample, "myfunction" ); print_r($array_sample); echo("

"); ?>

Array ( [A] => Mango [B] => Mango [C] => Mango )

In the above example, every value is replaced with the Mango value.

It is important to note that array_walk() cannot be used to modify array keys. The array_walk() can be defined as ( &$value, $key ), but not as ( &$value, & $key ).

Additionally, PHP does not alter a key even if it does not complain or warn. Even if there was declare ( strict_types=1 ), PHP ignored the argument type when calling array_walk() .

According to the code above, the tag is used to read the array conveniently and neatly. Without the tag, the outcome is a one-line array that is difficult to understand and messy.

What is PHP array-walk?

PHP’s array_walk() method is a built-in function. Regardless of the position of the pointer, the array_walk() function traverses the entire array and applies a callback function or user-defined function to each member. The keys and values of the array elements are parameters for the callback function.

Moreover, array_walk() is not affected by the internal array pointer of array . The array_walk() will walk through the entire array regardless of the pointer position. Based on the PHP Documentation.

What are the 3 types of PHP arrays?

  • Numeric arrays are arrays that contain a number index.
  • Associative arrays are arrays that have named keys.
  • Multidimensional arrays are arrays that hold additional arrays.

Summary

In summary, we learned how to use array_walk in PHP by analyzing example programs that demonstrated the different functions. You can now utilize complex arrays in the coding of your own programs.

Lastly, if you want to learn more about PHP array_walk , please leave a comment below. We’ll be happy to hear it!

Leave a Comment Cancel reply

You must be logged in to post a comment.

Источник

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