php array walk code example

Example 1: php array_walk

$arr = array(1, 2, 3);
// Call function on every item.
// Sign $item as reference to work on original item.
array_walk($arr, function(&$item, $key, $myParam){
  $item *= 2;
}, 'will be in myParam');
// $arr now is [2, 4, 6]

Example 2: php array walk

<?php
/*
*   For One Dimensional Array
*/
$alphabets = array(
    'a'  =>  'apple',
    'b'  =>  'ball',
    'c' =>  'cat',
);

array_walk($alphabets, 'myFunc', 'for');

function myFunc($value, $key, $param)
{
    echo "$key $param $value <br>";
}
?>
/*
Out Put:- 
a for apple
b for ball
c for cat
*/
 <?php
/*
*   For Two Dimensional Arrays:-  array_walk_recursive() 
**/
$alphabets = array(
    'a'  =>  'apple',
    'b'  =>  'ball',
    'c' =>  'cat',
    array(
        'd' =>  'dog',
        'e' =>  'elephant',
    )
);

array_walk_recursive($alphabets, 'myFunc2', 'for' );

function myFunc2($value, $key, $param){
    echo "$key $param $value <br><br>";
};
?>

Tags:

Php Example