Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

array_walk an anonymous function

Tags:

php

Is there a way I can get this array walk with my anonymous function to set the values?

$url = array('dog', 'cat', 'fish');  array_walk($url, function(&$value, &$key) {     $url[$key] = str_replace('dog', '', $value); });  echo '<pre>'; print_r($url); echo '</pre>'; 
like image 558
JREAM Avatar asked Apr 08 '12 20:04

JREAM


People also ask

What is array_walk?

The array_walk() function runs each array element in a user-defined function. The array's keys and values are parameters in the function. Note: You can change an array element's value in the user-defined function by specifying the first parameter as a reference: &$value (See Example 2).

What exactly is the the difference between Array_map array_walk and Array_filter?

The resulting array of array_map has the same length as that of the largest input array; array_walk does not return an array but at the same time it cannot alter the number of elements of original array; array_filter picks only a subset of the elements of the array according to a filtering function.


1 Answers

You are already passing the value by reference, so just do the following:

array_walk($url, function(&$value, &$key) {     $value = str_replace('dog', '', $value); }); 
like image 89
Tim Cooper Avatar answered Sep 28 '22 02:09

Tim Cooper