top of page
Search
  • Writer's pictureJayant Kumar

How to use array_walk() in PHP?

Updated: Dec 1, 2021



We have seen many scenarios where developers want to change values in array without creating in array. PHP have a function which will change the value inside array and will return the same array without any hustle.


Let's say, we have associate array like below

 $array = array(
  array(
  'name' => 'Sachin',
  'class' => '9',
  'school' => '-' 
  ),
  array(
  'name' => 'Rahul',
  'class' => '10',
  'school' => '-' 
  )
  );

And we want to change the school value with a School name.


solution:

We know our variable name which is `$array`

array_walk($array, function(&$value, $key) {
    $value['school'] = 'School Name';
});

Or if you have any variable which contains a school name, you can also use the your variable in array_walk with use function.


$schoolname = 'School Name';

// to change values of school key
array_walk($array, function(&$value, $key) use($schoolname) {
    $value['school'] = $schoolname;
});

See the overall code below:


$array = array(
  array(
  'name' => 'Sachin',
  'class' => '9',
  'school' => '-' 
  ),
  array(
  'name' => 'Rahul',
  'class' => '10',
  'school' => '-' 
  )
  );
  
  // variable contains school name
  $schoolname = 'School Name';

// to change values of school key
array_walk($array, function(&$value, $key) use($schoolname) {
    $value['school'] = $schoolname;
});

echo "<pre>"; print_r($array);die;

Hope it helps :) :)

29 views0 comments

Recent Posts

See All
bottom of page