[SOLVED] Apply simple function to array with array_walk?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
JAB Creations
DevNet Resident
Posts: 2341
Joined: Thu Jan 13, 2005 6:44 pm
Location: Sarasota Florida
Contact:

[SOLVED] Apply simple function to array with array_walk?

Post 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
Last edited by JAB Creations on Wed Nov 26, 2008 3:54 pm, edited 1 time in total.
User avatar
JAB Creations
DevNet Resident
Posts: 2341
Joined: Thu Jan 13, 2005 6:44 pm
Location: Sarasota Florida
Contact:

Re: Apply simple function to array with array_walk?

Post 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;
}
?>
Post Reply