array_walk


php128 apg

APPLY Apply a user supplied function to every member of an ARRAY.





This function is not affected by the internal array pointer of $array.

This function will walk through the entire $array regardless of pointer position.

The $callback has typically two parameters.

The $array parameter's value being the first, and the key/index second.

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.

Many internal functions 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 $userdata is supplied, it will be passed as the third parameter to the $callback.

Since 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).

Previously, if the $callback function required more than 2 parameters, an error of level E_WARNING would be generated each time this function calls $callback.



<?php

bool array_walk 
arr &$array , callable $callback [, 
                                                          
mix $userdata NULL ] )
 

where,

&
$array The input ARRAY

$callback The function to be used as the user-defined function
                        
$userdata The third parameter to be passed to the callback function

?> 

&$array


The input ARRAY.



$callback


The function to be used as the user-defined function.



$userdata


The third parameter to be passed to the callback function.



<?php

 ArgumentCountError 
extends TypeError {
/* Inherited properties */
protected string $message ;
protected 
int $code ;
protected 
string $file ;
protected 
int $line ;
/* Inherited methods */
final public Error::getMessage void ) : string
final public Error::getPrevious void ) : Throwable
final public Error::getCode void ) : mixed
final public Error::getFile void ) : string
final public Error::getLine void ) : int
final public Error::getTrace void ) : array
final public 
Error::getTraceAsString void ) : string
public Error::__toString void ) : string
final private Error::__clone void ) : void
}

?> 

  1 EXERCISE   

<?php

function eprodi($val01$key01)
{
$x01 bcmul($val01$key01);
echo 
$val01 ' * '$key01 ' = ' $x01 '<br>';
}

$arr01a = [ 1234];

echo 
'The given $arr01a:<br>';
print_r($arr01a);
echo 
'<br><br>';

array_walk($arr01a"eprodi");

?> 

 RESULT   

The given $arr01a:
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 )

1 * 0 = 0
2 * 1 = 2
3 * 2 = 6
4 * 3 = 12
5 * 4 = 20


  2 EXERCISE   

<?php

function prodiv02 ($val02$key02$fac02)
{
$i01 bcmul($val02$key02);
$j01 bcdiv($i01$fac025);
echo 
'( ' $val02 '&nbsp;*&nbsp;' $key02 
             
' )&nbsp;/&nbsp;' $fac02 ' = ' $j01 '<br>';
}

$arr02 = [ 1234];

echo 
'The given $arr02:<br>'
print_r($arr02);
echo 
'<br><br><br>';

@
array_walk($arr02"prodiv02"5);

?> 

 RESULT   

The given $arr02:
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 )

( 1 * 0 ) / 5 = 0.00000
( 2 * 1 ) / 5 = 0.40000
( 3 * 2 ) / 5 = 1.20000
( 4 * 3 ) / 5 = 2.40000
( 5 * 4 ) / 5 = 4.00000


  3 EXERCISE   

<?php

function comp03($val03$key03$nmr03)
{
echo 
$nmr03 '&nbsp;&nbsp;' 
         
$val03 '&nbsp;&nbsp;(' 
         
$key03 .  ')<br>';
}

$arr03 = [ "R" => "RED"
                
"G" => "GREEN"
                
"B" => "BLUE"
        
"WHITE" => [ 255,255,255 ] ];

echo 
'The given $arr03:<br><pre>';
print_r($arr03);
echo 
'</pre><br><br>';

@
array_walk($arr03"comp03""Component: ");

?> 

 RESULT   

The given $arr03:
Array
(
[R] => RED
[G] => GREEN
[B] => BLUE
[WHITE] => Array
(
[0] => 255
[1] => 255
[2] => 255
)

)

Component: RED (R)
Component: GREEN (G)
Component: BLUE (B)
Component: Array (WHITE)


See this same exercise handled by the array_walk_recursive function.


  4 EXERCISE   

<?php

echo "Testing array_walk() : basic functionality.";

// regular array
$fruits = array("lemon""orange""banana""apple");

echo 
'<br><br>The given $fuits;<br>';
var_dump($fruits);
echo 
'<br>';

function 
test_print($item$key)
{
   
// dump the arguments to check
   // that they are passed
   // with proper type
   
var_dump($item); // value
   
var_dump($key);  // key
   
echo "<br><br>";
   
// new line to separate the 
   // output between each element
}
function 
with_userdata($item$key$user_data)
{
   
// dump the arguments to check
   // that they are passed
   // with proper type
   
var_dump($item); 
   
// value
   
var_dump($key);
   
// key
   
var_dump($user_data);
   
// user supplied data
   
echo "<br><br>";
   
// new line to separate the 
   // output between each element
}

echo 
"<br><br>With default parameters 
                     to show array contents:<br>"
;
var_dumparray_walk($fruits'test_print'));

echo 
"<br><br>With all parameters:<br>";
var_dumparray_walk($fruits'with_userdata'"Added"));

?>

  5 EXERCISE   

<?php

echo "Testing array_walk() : basic functionality.";

// associative array
$fruits = [ "d" => "lemon"
                
"a" => "orange"
                
"b" => "banana"
                
"c" => "apple" ];

echo 
'<br><br>The given $fuits;<br>';
var_dump($fruits);
echo 
'<br>';

function 
test_alter(&$item$key$prefix)
{
  
// dump the arguments to check 
  // that they are passed
  // with proper type
  
var_dump($item);
  
// value
  
var_dump($key);
  
// key
  
var_dump($prefix);
  
// additional argument passed 
  // to callback function
  
echo "<br><br>";
  
// new line to separate the 
  // output between each element
}

function 
test_print($item$key)
{
  
// dump the arguments to check 
  // that they are passed
  // with proper type
  
var_dump($item);
  
// value
  
var_dump($key);
  
// key
  
echo "<br><br>";
  
// new line to separate the 
  // output between each element
}

echo 
"<br><br>With default parameters 
                     to show array contents:<br>"
;
var_dump(array_walk($fruits'test_print'));

echo 
"<br><br><br>With one optional parameter 
                      to modify contents:<br>"
;
var_dump (array_walk($fruits'test_alter''fruit'));

echo 
"<br><br><br>With default parameters 
                    to show modified array contents:<br>"
;
var_dump (array_walk($fruits'test_print'));

?>

  6 EXERCISE   

<?php

/*
 * Testing array_walk() with 
 * following types of 'input' arrays:
 *    integer, float, string, 
 *    bool, null, empty & mixed
*/

function print_value($value$key$count)
{
  echo  
$count." : ".$key." ".$value."<br>";
}

echo 
"Testing array_walk() : 'input' array 
                with different values.<br>"
;

// different arrays as input
$input_values = array(

       
// integer values
/*1*/  
array(10, -10023, -0410x5A0X1F, -0x6E),

       
// float value
       
array(3.40.8, -2.96.25e28.20E-3),

       
// string values
       
array('Mango'"Apple"'Orange'"Lemon"),

       
// bool values
/*4*/  
array(truefalseTRUEFALSE),

       
// null values
       
array(nullNULL),

       
// empty array
       
array(),

       
// binary array
       
array(b"binary"),

       
// mixed array
/*8*/  
array(168.345"Fruits"
                                  
truenull
                                  
FALSE, -98
                                 
0.005'banana')
);

for(
$count 0$count count($input_values); $count++) {
  echo 
"<br><br>Iteration: ".($count 1)."<br>";
  
var_dumparray_walk($input_values[$count], 
                                                             
"print_value"
                                                              
$count+1));
}

?>

  7 EXERCISE   

<?php

/*
 * Testing array_walk() with an array 
 * having subarrays as elements
*/

echo "Testing array_walk() : array with subarray.<br><br>";

function 
callback($value$key)
{
   
// dump the arguments to check 
   // that they are passed
   // with proper type
   
var_dump($key);
   
// key
   
var_dump($value);
   
// value
   
echo "<br><br>"
   
// new line to separate the 
   // output between each element
}

$input = array(
  array(),
  array(
1),
  array(
1,2,3),
  array(
"Mango""Orange"),
  array(array(
123))
);

var_dumparray_walk$input"callback"));

?>

  8 EXERCISE   

<?php

/*
 * Testing array_walk() with an 
 * array having reference variables
*/

echo "Testing array_walk() : array with 
                           references.<br><br>"
;

$value1 10;
$value2 = -20;
$value3 = &$value1;
$value4 50;

// 'input' array containing 
// references to above variables
$input = array(&$value1
                       &
$value2
                     -
35
                       &
$value3
                       
0
                       &
$value4);

function 
callback($value$key)
{
   
// dump the arguments to check
   // that they are passed
   // with proper type
   
var_dump($key);  // key
   
var_dump($value); // value
   
echo "<br><br>"
   
// new line to separate the output
   // between each element
}

var_dumparray_walk($input"callback"));

?>

  9 EXERCISE   

<?php

/*
 * Passing 'input' argument 
 * as an associative array
 * with Numeric & string keys
*/

echo "Testing array_walk() : 'input' as an associative array.";

function 
for_numeric($value$key$user_data)
{
  
// dump the input values to see if they are
  // passed with correct type
  
var_dump($key);
  
var_dump($value);
  
var_dump($user_data);
  echo 
"<br><br>"
  
// new line to separate the output
  // between each element
}

function 
for_string($value$key)
{
  
// dump the input values to see if they are
  // passed with correct type
  
var_dump($key);
  
var_dump($value);
  echo 
"<br><br>";
  
// new line to separate the 
  // output between each element
}

function 
for_mixed($value$key)
{
  
// dump the input values to 
  // see if they are
  // passed with correct type
  
var_dump($key);
  
var_dump($value);
  echo 
"<br><br>";
  
// new line to separate the 
  // output between each element
}

// Numeric keys
$input = array( => 25=> 12=> -80, -=> 100=> 30);
echo 
"<br><br><br>Associative array with numeric keys:<br><br>";
var_dumparray_walk($input"for_numeric"10));

// String keys
$input = array( "a" => "Apple"'b' => 'Bananna'
                        
"c" => "carrot"'o' => "Orange");
echo 
"<br><br><br>Associative array with string keys:<br><br>";
var_dumparray_walk($input"for_string"));

// binary keys
$input = array( b"a" => "Apple"b"b" => "Banana");
echo 
"<br><br><br>Associative array with binary keys:<br><br>";
var_dumparray_walk($input"for_string"));

// Mixed keys - numeric/string
$input = array( => 1=> 2"a" => "Apple"
                                              
"b" => "Banana"=>3);
echo 
"<br><br><br>Associative array with numeric/string keys:<br><br>";
var_dumparray_walk($input"for_mixed"));

?>

  10 EXERCISE   

<?php

/*
* Passing anonymous(run-time) callback function 
* with following variations:
*   with one parameter
*   two parameters
*   three parameters
*   extra parameters
*   without parameters
*/

echo "Testing array_walk() : anonymous function as callback.";

$input = array(25100);

echo 
"<br><br><br>Anonymous function 
                              with one argument:<br>"
;
var_dumparray_walk($input
              function(
$value) { var_dump($value); echo "<br>"; }));

echo 
"<br><br><br>Anonymous function 
                              with two arguments:<br>"
;
var_dumparray_walk($input
                  function(
$value$key) { 
                              
var_dump($key); var_dump($value);
                              echo 
"<br>"; }));

echo 
"<br><br><br>Anonymous function 
                             with three arguments:<br>"
;
var_dumparray_walk($input
                 function(
$value$key$user_data) { 
                                
var_dump($key); 
                                
var_dump($value); 
                                
var_dump($user_data); 
                                echo 
"<br>"; }, 10));

echo 
"<br><br><br>Anonymous function 
                            with null argument:<br>"
;
var_dumparray_walk$input, function() { echo "1<br>"; }));

?>

  11 EXERCISE   

<?php

/*
 * Passing different types of 
 * callback functions to array_walk()
 *   without parameters
 *   with less and more parameters
*/

echo "Testing array_walk() : callback function variation.";

$input = array('Apple''Banana''Mango''Orange');

echo 
"<br><br><br>callback function 
                        with both parameters:<br>"
;
function 
callback_two_parameter($value$key)
{
   
// dump the arguments to 
   // check that they are passed
   // with proper type
   
var_dump($key);
   
// key
   
var_dump($value);
   
// value
   
echo "<br>";
   
// new line to separate the 
   // output between each element
}
var_dumparray_walk($input'callback_two_parameter'));

echo 
"<br><br><br>callback function 
                         with only one parameter:<br>"
;
function 
callback_one_parameter($value)
{
   
// dump the arguments to check 
   // that they are passed
   // with proper type
   
var_dump($value);
   
// value
   
echo "<br>";
   
// new line to separate the 
   // output between each element
}
var_dumparray_walk($input'callback_one_parameter'));

echo 
"<br><br><br>callback function 
                       without parameters:<br>"
;
function 
callback_no_parameter()
{
  echo 
"callback3() called:<br>";
}
var_dumparray_walk($input'callback_no_parameter'));

echo 
"<br><br><br>passing one more parameter 
                      to function with two parameters:<br>"
;
var_dumparray_walk($input'callback_two_parameter'10));

?>