Page 1 of 1

[SOLVED] Apply simple function to array with array_walk?

Posted: Wed Nov 26, 2008 12:27 pm
by JAB Creations
I'm pretty sure PHP's array_walk function is what I want to use to apply a function to manipulate all the values in an array. That function essentially removes all non-alphanumeric characters and executes some replacements of characters such as ampersands as the output will be used in URL's. However I'm pretty sure I'm not applying this correctly and I think the issue is that I normally call the function passing a parameter.

Here is what I have and unfortunately it doesn't seem to be a well documented function so a little help would be greatly appreciated. :mrgreen:

Code: Select all

<?php
function name_base($name1)
{
 $name2 = str_replace(" ", "_", $name1);
 $name3 = str_replace("&", "and", $name2);
 $name4 = strtolower($name3);
 return $name4;
}
 
echo "Before ...:<br />\n";
print_r($fruits);
 
array_walk($fruits, 'name_base', 'fruit');
echo "<br />... and after:<br />\n";
 
$new = array_walk($fruits, name_base);
print_r($new);
?>
This currently outputs the following...
Before ...:
Array ( [0] => Lemon Fresh [1] => Orange Twist [2] => Banana Blah [3] => Apple Juice )
... and after:
1

Re: Apply simple function to array with array_walk?

Posted: Wed Nov 26, 2008 3:53 pm
by JAB Creations
SUCCESS!

Code: Select all

<?php
$fruits = array("Lemony & Fresh","Orange Twist","Apple Juice");
 
array_walk($fruits, 'name_base');
 
function name_base($key)
{
 $name2 = str_replace(" ", "_", $key);
 $name3 = str_replace("&", "and", $name2);
 $name4 = strtolower($name3);
 echo $name4.'<br />';
 //return $name4;
}
?>