Log in

View Full Version : Permantly update array w/array_walk or assign to new?



JAB Creations
11-26-2008, 11:34 PM
I've successfully applied PHP's array_walk function to an array though only temporarily. The issue is PHP isn't actually applying the function's effects to the array...nor have I figured out how to save the effects to a new array...so in effect I have no idea how to use array_walk in a reusable manner! This means I'd have to apply it once each time I want to use the array...in the same file!

Here is what I have...


<?php
$fruits = array("Lemony & Fresh","Orange Twist","Apple Juice");

$test = array_walk($fruits, 'name_base');
$fruits_fixed = array($test);

function name_base($key)
{
$name2 = str_replace(" ", "_", $key);
$name3 = str_replace("&", "and", $name2);
$name4 = strtolower($name3);
echo $name4.'<br />';
return $name4;
}
echo '<br />';
print_r($fruits_fixed);
echo '<br /><br />';
if (is_array($fruits_fixed)) {echo 'is array';}
else {echo 'not array';}
echo '<br /><br />';

var_dump($fruits_fixed);
?>

techietim
11-26-2008, 11:44 PM
Instead of array_walk, use array_map

JAB Creations
11-26-2008, 11:51 PM
I [Thank] you very much! (for saving my sanity!)


<?php
$fruits = array("Lemony & Fresh","Orange Twist","Apple Juice");

print_r($fruits);
echo '<br />';

function name_base($key)
{
$name2 = str_replace(" ", "_", $key);
$name3 = str_replace("&", "and", $name2);
$name4 = strtolower($name3);
echo $name4.'<br />';
return $name4;
}
echo '<br />';


$test = array_map('name_base', $fruits);
$fruits_fixed = $test;
echo '<br />';
print_r($fruits_fixed);
?>