thank_you
thank_you

Reputation: 11107

Altering an Array with Array Walk

I have an array that I want to alter. I thought that array_walk would be the way to go but I'm having trouble figuring out how to collect that data from array_walk, deleting the data from the old array, and inserting the new data. How should I go about doing this? Here is the code.

$width_array = array(

"2.5%",

"2.6%",

"2.7%",

"2.8%",

);

function adjust_the_width($value) 

{

$value = $value * 2;

}

array_walk($width_array, "adjust_the_width");

$random_width = array_rand($width_array, 10);

Upvotes: 0

Views: 139

Answers (1)

Lucas Green
Lucas Green

Reputation: 3959

You where likely looking for array_map, example below:

<?
$width_array = array(
    "2.5%",
    "2.6%",
    "2.7%",
    "2.8%",
);

function adjust_the_width($value) {
    return $value * 2;
}

$width_array = array_map("adjust_the_width", $width_array);
$random_width = array_rand($width_array, count($width_array));


var_dump($width_array);

Note: the percentages are dropped from the calculations because PHP interprets the string "2.5%" as a float value when it is multiplied by 2.

Also, array_map supplies each element as the parameter to the function provided and uses it's return value to fill the same place in the new array that array_map builds.

This is also why I assign $width_array = array_map(..., array_map builds a new array, it does not replace the old one by default.

You can also do this if you'd rather not build the intermediate array:

foreach($width_array as &$width) {
    $width = $width * 2;
}

var_dump($width_array);

This walks the array and modifies each element as a reference to it's location (that's what &$width means).

Without the '&' this foreach loop will do nothing but chew cpu cycles.

Upvotes: 2

Related Questions