Jack Jack - 1 month ago 18
PHP Question

php array_map to every 'arr' element in associative array

I got hte following array:

[
[
'arr1' => 'string',
'arr2' => 5000000,
...//hundreds of other elements which I want to preserve
],
[
'arr1' => 'string2',
'arr2' => 4000000,
...//other elements
]
]


I need to divide only every 'arr2' element by 10000 or apply 'intval' to it. I tried to use array_map or array_walk but it said I need to pass an array to it while I tried to pass it a certain element. Also these functions work with every element while I need to work only with 1 element in subarray. There may be hundreds of other elements in subarray which I need to preserve. Thank you.

Fky Fky
Answer

Try to use array_walk() http://php.net/manual/fr/function.array-walk.php like this :

array_walk($yourarray, function(&$value) {
   if(isset($value['arr2']) && is_string($value['arr2'])){ // or test numeric is_numeric()
     $value['arr2'] = intval($value['arr2']); // or divide $value['arr2']/1000 
   }
});