The Most Active and Friendliest
Affiliate Marketing Community Online!

“AdsEmpire”/  Direct Affiliate

Tip : apply a function to each array element

D

dman_2007

Guest
If you wish to apply a function to each array element then you can use array_walk function to automate the task instead of using foreach to loop through array and call each function manually. For example :

Code:
<?php
  function test_function($value, $key)
  {
    echo $key, ' => ', $value, '<br />';  
  }
  
  $array_var = array(1, 2, 3, 4, 5, 6, 7, 8, 9);
  
  array_walk($array_var, 'test_function');
?>

If you wish to pass any data to the call back function you can do so by passing that data as third parameter to array_walk function. For example,

Code:
<?php
  function show_exponent(&$value, $key, $pow)
  {
    echo $value, ' => ', pow($value, $pow), '<br />';  
  }
  
  $array_var = array(1, 2, 3, 4, 5, 6, 7, 8, 9);

  array_walk($array_var, 'show_exponent', 2);
?>

Another thing to note is that the changes made to the array elements in the callback function doesn't affect the original array. If you wish to alter the original values of array elements in the callback function then pass array elements to the callback function as reference. For example,

Code:
<?php
 
 function show_exponent(&$value, $key, $pow)
 {
   $value =  pow($value, $pow);  
 }
  
  $array_var = array(1, 2, 3, 4, 5, 6, 7, 8, 9);

  array_walk($array_var, 'show_exponent', 2);
  
  print_r($array_var);
  
?>

the code given above will print the changed array.

If your array elements are array themselves and you want to apply the callback function to their elements as well then use array_walk_recursive function.
 
banners
Back