downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | conferences | my php.net

search for in the

array> <array_walk_recursive
[edit] Last updated: Fri, 26 Apr 2013

view this page in

array_walk

(PHP 4, PHP 5)

array_walkApply a user function to every member of an array

Description

bool array_walk ( array &$array , callable $funcname [, mixed $userdata = NULL ] )

Applies the user-defined function funcname to each element of the array array.

array_walk() is not affected by the internal array pointer of array. array_walk() will walk through the entire array regardless of pointer position.

Parameters

array

The input array.

funcname

Typically, funcname takes on two parameters. The array parameter's value being the first, and the key/index second.

Note:

If funcname needs to be working with the actual values of the array, specify the first parameter of funcname as a reference. Then, any changes made to those elements will be made in the original array itself.

Note:

Many internal functions (for example strtolower()) will throw a warning if more than the expected number of argument are passed in and are not usable directly as funcname.

Only the values of the array may potentially be changed; its structure cannot be altered, i.e., the programmer cannot add, unset or reorder elements. If the callback does not respect this requirement, the behavior of this function is undefined, and unpredictable.

userdata

If the optional userdata parameter is supplied, it will be passed as the third parameter to the callback funcname.

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

If function funcname requires more parameters than given to it, an error of level E_WARNING will be generated each time array_walk() calls funcname. These warnings may be suppressed by prepending the PHP error operator @ to the array_walk() call, or by using error_reporting().

Examples

Example #1 array_walk() example

<?php
$fruits 
= array("d" => "lemon""a" => "orange""b" => "banana""c" => "apple");

function 
test_alter(&$item1$key$prefix)
{
    
$item1 "$prefix$item1";
}

function 
test_print($item2$key)
{
    echo 
"$key$item2<br />\n";
}

echo 
"Before ...:\n";
array_walk($fruits'test_print');

array_walk($fruits'test_alter''fruit');
echo 
"... and after:\n";

array_walk($fruits'test_print');
?>

The above example will output:

Before ...:
d. lemon
a. orange
b. banana
c. apple
... and after:
d. fruit: lemon
a. fruit: orange
b. fruit: banana
c. fruit: apple

See Also



array> <array_walk_recursive
[edit] Last updated: Fri, 26 Apr 2013
 
add a note add a note User Contributed Notes array_walk - [41 notes]
up
2
http://alex.moutonking.com/wordpress
2 years ago
For completeness one has to mention the possibility of using this function with PHP 5.3 closures:

<?php
$names
= array("D\'Artagnan", "Aramis", "Portos");
array_walk($names, function(&$n) {
 
$n = stripslashes($n);
});
?>

The trap with array_walk being it doesn't return the array, instead it's modified by reference.
up
1
jerk at yoosic dot de
6 years ago
if you want to modify every value of an multidimensional array use this function used here:

<?php

$array
= array (1=>1, 2=> 2, 3 => array(1=>11, 2=>12, 3=>13));
$text = "test";

function
modarr(&$array, $text) {
        foreach (
$array as $key => $arr) {
                if(
is_array($arr)) $res[$key] = modarr(&$arr,$text);
               
// modification function here
               
else $res[$key] = $arr.$text;
                }
        return
$res;
}

$erg = modarr($array, $text);

print_r($erg); 

?>

result will be_

<?php
Array ( [1] => 1test [2] => 2test [3] => Array ( [1] => 11test [2] => 12test [3] => 13test ) )
?>
up
1
ibolmo
7 years ago
If anyone is interested to implement the array_walk functionality to a string. I've made this handy function. Note that this can be easily extended for any type of purpose. I've used this to convert from a string of bytes to a hex string then back from hex to a byte string.
<?php
function string_walk($string,$funcname)
{
    for(
$i=0;$i<strlen($string);$i++) {
       
call_user_func($funcname,$string{$i});
    }
}

function
yourFunc($val)
{
    echo
$val.' ';
}

string_walk('interesting','yourFunc');
//ouput: i n t e r e s t i n g
?>
up
1
webmaster at tmproductionz dot com
7 years ago
to the note right before this one.  that will only trim leading and trailing white space. if you want to trim white space inside the string (ie 'hello     world' to 'hello world') you should use this:

$val = preg_replace ( "/\s\s+/" , " " , $val ) ;

this will also trim leading and trailing white space.
up
4
manuscle at gmail dot com
1 year ago
example with closures, checking and deleting value in array:

<?php
$array
= array('foo' => 'bar', 'baz' => 'bat');

array_walk($array, function($val,$key) use(&$array){
    if (
$val == 'bar') {
        unset(
$array[$key]);
    }
});

var_dump($array);
up
4
@jfredys
2 years ago
I was looking for trimming all the elements in an array, I found this as the simplest solution:

<?php
array_walk
($ids, create_function('&$val', '$val = trim($val);'));
?>
up
2
arekandrei at yandex dot ru
3 years ago
You can use lambda function as a second parameter:

<?php
array_walk
($myArray, function(&$value, $key){
   
// if you want to change array values then "&" before the $value is mandatory.
});
?>

Example (multiply positive values by two):

<?php
$myArray
= array(1, 2, 3, 4, 5);

array_walk($myArray, function(&$value, $index){
    if (
$value > 0) $value *= 2;
});
?>
up
2
Andrzej Martynowicz at gmail dot com
7 years ago
It can be very useful to pass the third (optional) parameter by reference while modifying it permanently in callback function. This will cause passing modified parameter to next iteration of array_walk(). The exaple below enumerates items in the array:

<?php
function enumerate( &$item1, $key, &$startNum ) {
  
$item1 = $startNum++ ." $item1";
}

$num = 1;

$fruits = array( "lemon", "orange", "banana", "apple");
array_walk($fruits, 'enumerate', $num );

print_r( $fruits );

echo
'$num is: '. $num ."\n";
?>

This outputs:

Array
(
    [0] => 1 lemon
    [1] => 2 orange
    [2] => 3 banana
    [3] => 4 apple
)
$num is: 1

Notice at the last line of output that outside of array_walk() the $num parameter has initial value of 1. This is because array_walk() does not take the third parameter by reference.. so what if we pass the reference as the optional parameter..

<?php
$num
= 1;

$fruits = array( "lemon", "orange", "banana", "apple");
array_walk($fruits, 'enumerate', &$num ); // reference here

print_r( $fruits );

echo
'$num is: '. $num ."\n";
echo
"we've got ". ($num - 1) ." fruits in the basket!";
?>

This outputs:
Array
(
    [0] => 1 lemon
    [1] => 2 orange
    [2] => 3 banana
    [3] => 4 apple
)
$num is: 5
we've got 4 fruits in the basket!

Now $num has changed so we are able to count the items (without calling count() unnecessarily).

As a conclusion, using references with array_walk() can be powerful toy but this should be done carefully since modifying third parameter outside the array_walk() is not always what we want.
up
1
selimacar at hotmail dot com
10 months ago
####### I intuitively tried to use array_walk function with PHP built-in function "abs($var)" but it did not work and got some warning message

<?php
$values
= array(-5,2,3,-8,4,-1,0);
array_walk($values, "abs");
?>

=> Warning: abs() expects exactly 1 parameter, 2 given in ...

###### Then I wrote this function :

<?php
function myAbs(&$val){
   
$val abs($val);
}
array_walk($values, "myAbs");
?>

##### It works!
up
0
espertalhao04 at hotmail dot com
4 months ago
here is a simple and yet easy to use implementation of this function.
the 'original' function has the problem that you can't unset a value.
with my function, YOU CAN!

<?php
function array_walk_protected(&$a,$s,$p=null)
{
    if(!
function_exists($s)||!is_array($a))
    {
        return
false;
    }
   
    foreach(
$a as $k=>$v)
    {
        if(
call_user_func_array($s,array(&$a[$k],$k,$p))===false)
        {
            unset(
$a[$k]);
        }
    }
}

function
get_name(&$e,$i,$p)
{
    echo
"$i: $e<br>";
    return
false;
}

$m=array('d'=>'33','Y'=>55);

array_walk_protected($m,'get_name');

var_dump($m); //returns array(0) { }
?>

i called it array_walk_protected because it is protected against the unexpected behavior of unsetting the value with the original function.

to delete an element, simply return false!!!
nothing else is needed!
unsetting $e, under your created function, will keep the same array as-is, with no changes!

by the way, the function returns false if $a is not array or $s is not a string!

limitations: it only can run user defined functions.
i hope you like it!
up
0
Maxim
1 year ago
Note that using array_walk with intval is inappropriate.
There are many examples on internet that suggest to use following code to safely escape $_POST arrays of integers:
<?php
array_walk
($_POST['something'],'intval'); // does nothing in PHP 5.3.3
?>
It works in _some_ older PHP versions (5.2), but is against specifications. Since intval() does not modify it's arguments, but returns modified result, the code above has no effect on the array and will leave security hole in your website.

You can use following instead:
<?php
$_POST
['something'] = array_map(intval,$_POST['something']);
?>
up
0
Hayley Watson
8 years ago
As well as being able to pass the array the callback will be working on by reference, one can pass the optional userdata parameters by reference also:
<?php

function surprise($x,$key,$xs)
{
   
//$key is unused here.
   
$x.='!';
   
array_push($xs,$x);
}

$array1 = array('this','that','the other');
$array2 = array();

array_walk($array1,'surprise',&$array2);

print_r($array1);
print_r($array2);
?>
Of course, that precise example would be better handled by array_map, but the principle is there.
up
0
Anonymous
8 years ago
If array_walk_recursive() is not present and you want to apply htmlentities() on each array element you can use this:

<?php
function array_htmlentities(&$elem)
{
  if (!
is_array($elem))
  {
   
$elem=htmlentities($elem);
  }
  else
  {
    foreach (
$elem as $key=>$value)
     
$elem[$key]=array_htmlentities($value);
  }
  return
$elem;
}
// array_htmlentities()
?>

If you want to output an array with print_r() and you have html in it this function is very helpful.
up
0
bisqwit at iki dot fi
8 years ago
It's worth nothing that array_walk can not be used to change keys in the array.
The function may be defined as (&$value, $key) but not (&$value, &$key).
Even though PHP does not complain/warn, it does not modify the key.
up
-1
op_adept at yahoo dot co dot uk
2 years ago
Prefix array values with keys and retrieve as a glued string, the original array remains unchanged. I used this to create some SQL queries from arrays.

<?php

function array_implode_prefix($outer_glue, $arr, $inner_glue, $prefix=false){
   
array_walk( $arr , "prefix", array($inner_glue, $prefix) );
    return
implode($outer_glue, $arr);
}

function
prefix(&$value, $key, array $additional){
   
$inner_glue = $additional[0];
   
$prefix = isset($additional[1])? $additional[1] : false;
    if(
$prefix === false) $prefix = $key;

   
$value = $prefix.$inner_glue.$value;
}

//Example 1:
$order_by = array("3"=>"ASC", "2"=>"DESC", "7"=>"ASC");
echo
array_implode_prefix(",", $order_by, " ");
//Output: 3 ASC,2 DESC,7 ASC

//Example 2:
$columns = array("product_id", "category_id", "name", "description");
$table = "product";

echo
array_implode_prefix(", ", $columns, ".", $table);
//Output:product.product_id, product.category_id, product.name, product.description

//Example 3 (function prefix) won't really be used on its own
$pre= "vacation";
$value = "lalaland";
prefix($value, $pre, array("."));
echo
$value;

//Output: vacation.lalaland

?>
up
0
gold[at]evolved.net.nz
1 month ago
For all those people trying to shoe-horn trim() into array_walk() and have found all these tricks to work around the issue with array_walk() passing 2 parameters to the callback...

Check out array_map().

http://php.net/array_map

It's all sorts of win.

For the record. I'm one of these people and after 15 years of php development I'm pleased to say that there's still things I'm learning. :)  I just found out about array_map() myself...
up
0
alex_stanhope at hotmail dot com
1 year ago
I wanted to walk an array and reverse map it into a second array.  I decided to use array_walk because it should be faster than a reset,next loop or foreach(x as &$y) loop.

<?php
$output
= array();
array_walk($input, 'gmapmark_reverse', $output);

function
gmapmark_reverse(&$item, $index, &$target) {
   
$target[$item['form_key']] = $index;
}
?>

In my debugger I can see that $target is progressively updated, but when array_walk returns, $output is empty.  If however I use a (deprecated) call-by-reference:

<?php
array_walk
($input, 'gmapmark_reverse', &$output);
?>

$output is returned correctly.  Unfortunately there's not an easy way to suppress the warnings:

<?php
@array_walk($input, 'gmapmark_reverse', &$output);
?>

doesn't silence them.  I've designed a workaround using a static array:

<?php
$reverse
= array();
array_walk($input, 'gmapmark_reverse');
// call function one last time to get target array out, because parameters don't work
$reverse = gmapmark_reverse($reverse);

function
gmapmark_reverse(&$item, $index = 0) {
  static
$target;
  if (!
$target) {
   
$target = array();
  }
  if (isset(
$item['form_key'])) {
   
$target[$item['form_key']] = $index;
  }
  return(
$target);
}
?>
up
0
tufanbarisyildirim at gmail dot com
1 year ago
Filter an array by using key.

<?php
    $product_1
= 'test';
   
$product_2 = 'test 2';

    function
array_key_filter($array,$callback = 'trim')
    {  
       
$filtered = array();
       
array_walk($array,function ($degeri,$degisken_adi) use (&$filtered,$callback)
        {  
            if(
$callback($degisken_adi))
            {
               
$filtered[$degisken_adi] =  $degeri;
            }  
        });

        return
$filtered;        
    }

   
#using

   
$degiskenler = array_key_filter(get_defined_vars(),function($key)
    {
        return
strpos($key,'product_') === 0;
    });

   
print_r($degiskenler);
?>
output:

Array
(
    [product_1] => test
    [product_2] => test 2
)
up
0
AskApache
2 years ago
Here's a handy function that illustrates using an array_walk that uses a create_function as the callback which in turn uses another array_walk with another create_function that outputs the global variables pretty-print style.

Note that by using $g=array() as the first arg for array_walk it isn't necessary to declare the array beforehand.

Other notes:  ob_start, (print), and array_walk all return true on success which is how the if processing works.

Using <?php !!$array; ?> returns true only if sizeof array is greater than 0, just a shortcut for <?php if(sizeof($array)>0);?> ... more in the php manual section on booleans.

The output is meant to be displayed inline on a page so the htmlspecialchars is called on the output.  The output is buffered by ob_start and is then output by echoing the return of ob_get_clean(), which returns the buffer and cleans the buffer.

DEBUG would need to be a defined constant for this to execute, personally I like to
<?php
if($_SERVER['REMOTE_ADDR']=='MYSTATICIPADDRESS') askapache_global_debug();
//or
if($_SERVER['REMOTE_ADDR']=='MYSTATICIPADDRESS') define('DEBUG',TRUE);
?>

<?php

function askapache_global_debug()
{
array_walk(
 
$g=array('_GET','_POST','_COOKIE','_SESSION','_ENV','_SERVER'),
  
create_function('$n','global $$n;
    if(
      !!$$n
      && ob_start()
      && (print "( $"."$n )\n")
      && array_walk($$n,
       create_function(\'&$v,$k\', \'echo "[$k] => $v\n";\'))
     )
    echo "<pre>".htmlspecialchars(ob_get_clean())."</pre>";'
  
)
);
}   
if(
DEBUG) askapache_global_debug();

?>
up
0
matthew at codenaked dot org
2 years ago
Using lambdas you can create a handy zip function to zip together the keys and values of an array. I extended it to allow you to pass in the "glue" string as the optional userdata parameter. The following example is used to zip an array of email headers:

<?php

/**
 * Zip together the keys and values of an array using the provided glue
 *
 * The values of the array are replaced with the new computed value
 *
 * @param array $data
 * @param string $glue
 */
function zip(&$data, $glue=': ')
{
    if(!
is_array($data)) {
        throw new
InvalidArgumentException('First parameter must be an array');
    }

   
array_walk($data, function(&$value, $key, $joinUsing) {
       
$value = $key . $joinUsing . $value;
    },
$glue);
}

$myName = 'Matthew Purdon';
$myEmail = 'matthew@example.com';
$from = "$myName <$myEmail>";

$headers['From'] = $from;
$headers['Reply-To'] = $from;
$headers['Return-path'] = "<$myEmail>";
$headers['X-Mailer'] = "PHP" . phpversion() . "";
$headers['Content-Type'] = 'text/plain; charset="UTF-8"';

zip($headers);

$headers = implode("\n", $headers);
$headers .= "\n";

echo
$headers;

/*
From: Matthew Purdon <matthew@example.com>
Reply-To: Matthew Purdon <matthew@example.com>
Return-path: <matthew@example.com>
X-Mailer: PHP5.3.2
Content-Type: text/plain; charset="UTF-8"
*/
?>
up
0
rustamabd at gmail dot com
3 years ago
Don't forget about the array_map() function, it may be easier to use!

Here's how to lower-case all elements in an array:

<?php
    $arr
= array_map('strtolower', $arr);
?>
up
0
erelsgl at gmail dot com
4 years ago
If you want to unset elements from the callback function, maybe what you really need is array_filter.
up
0
jab_creations_-at_-yahoo_-dot-_com
4 years ago
Unfortunately I spent a lot of time trying to permanently apply the effects of a function to an array using the array_walk function when instead array_map was what I wanted. Here is a very simple though effective example for those who may be getting overly frustrated with this function...

<?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);
?>
up
0
peterzuzek AT gmail DOT com
4 years ago
I had some problems using this function - it didn't want to apply PHP-defined functions. So I decided to write my own - here it is. I had to use some generic-programming skills, didn't really checked the speed (I think it could be slow)... I believe it could be much better, but I don't know, how - well, I guess multiple array support and recursion would be nice. So?

Prototype:
bool arrayWalk(array &$arry, callback $callback, mixed $params=false)

<?php

   
function arrayWalk(&$arry, $callback, $params=false) {
       
$P=array(""); // parameters
       
$a=""; // arguement string :)

       
if($params !== false) { // add parameters
           
if(is_array($params)) { // multiple additional parameters
               
foreach($params as $par)
                    {
$P[]=$par; }
            }
            else
// just one additional
               
{ $P[]=$params; }
        }

        for(
// create the arguement string
           
$i=0; isset($P[$i]); ++$i
       
)
            {
$a.='$'.chr($i + 97).', '; } // random argument names

       
$a=substr($a, 0, -2); // to get rid of the last comma and two spaces

       
$func=create_function($a, 'return '.$callback.'('.$a.');'); // the generic function

       
if(is_callable($func)) {
            for(
// cycle through array
               
$i=0; isset($arry[$i]); ++$i
           
) {
               
$P[0]=$arry[$i]; // first element must be the first argument - array value
               
$arry[$i] = call_user_func_array($func, $P); // assign the new value obtained by the generic function
           
}
        }
        else
            { return
false; } // failure - function not callable

       
return true; // success!
   
} // arrayWalk()

?>

One big problem I've noticed so far - for example, if you wanted to use str_replace on the array, you'd fail - simply because of the arguement order of str_replace, where the string modified is the third arguement, not the first as arrayWalk requires.

So, still some work left...
up
0
diyism
4 years ago
When i pass the third parameter by reference in php5.2.5,
happened this: Warning: Call-time pass-by-reference has been deprecated - argument passed by value...

And to set allow_call_time_pass_reference to true in php.ini won't work, according to http://bugs.php.net/bug.php?id=19699   thus to work around:

<?php
array_walk
($arrChnOut, create_function('&$v, $k, $arr_rtn', 'if ($k{0}!="_") {$arr_rtn[0]["_".$v[\'ID\']]=$v; unset($arr_rtn[0][$k]);}'), array(&$arrChnOut));
?>
up
0
example at user dot com
4 years ago
On array_walk and create_function used within a class scope - Anonymous functions are out of scope.  So, if you want to access $this within the anonymous function, you'd have to pass it through the third parameter...

<?php

// example copies all values into $this where key is the same as property name

array_walk($array, create_function('$v,$k,&$that', 'if (property_exists($that,$k)) {$that->$k = $v;}'), $this);

// or, switch it around and array_walk the object

array_walk($this, create_function('&$v,$k,$array','if (array_key_exists($k,$array)) {$v = $array[$k];}'), $array);

?>
up
0
harmor
4 years ago
I just wanted a function to trim all the array elements.  Here is a non-recursive version:

<?php
$data
= array('       a',' b','    c        d   ');

function
_trim(&$value)
{
   
$value = trim($value);   
}

function
array_trim($arr)
{
   
array_walk($arr,"_trim");
    return
$arr;
}

$arr = array_trim($data);

echo
'<pre>';
var_dump($arr);
echo
'</pre>';

$single = implode(' ',$arr);

echo
'<pre>';
var_dump($single);
echo
'</pre>';
?>

Output:

array(3) {
  [0]=>
  string(1) "a"
  [1]=>
  string(1) "b"
  [2]=>
  string(10) "c        d"
}

string(14) "a b c        d"
up
0
mike >> mike AT debitage.com
5 years ago
<?php
  
/**
    *    class.ArrayTool.php lets you search an array based on key => value pairs
    *
    *   @version 1.0
    *   @ 1-11-2008
    *   @author Mike Volmar
    *
    *    Object for converting between array key and value
    *
    */   

class ArrayTool {

    var
$mydata = array();
    var
$flag = 0;
    var
$results;
   
    function
ArrayTool(){

    }
   
    function
tellAll(){
       
print_r($this->mydata);
    }
   
    function
setArray($data){
       
$this->mydata = $data;
    }

    function
getKey($input){
        foreach(
$this->mydata as $key => $value){
            if((
$this->flag == 0)&&($input == $value)){
               
$this->results = $key;
               
$this->flag = 1;
            }
        }
       
$this->flag = 0;
        return
$this->results;       
    }

    function
getValue($input){
        foreach(
$this->mydata as $key => $value){   
            if((
$this->flag == 0)&&($input == $key)){
               
$this->results = $value;
               
$this->flag = 1;
            }
        }
       
$this->flag = 0;
        return
$this->results;
    }

}

?>
up
0
ludvig dot ericson at gmail dot com
7 years ago
In response to 'ibolmo', this is an extended version of string_walk, allowing to pass userdata (like array_walk) and to have the function edit the string in the same manner as array_walk allows, note now though that you have to pass a variable, since PHP cannot pass string literals by reference (logically).

<?php
function string_walk(&$string, $funcname, $userdata = null) {
    for(
$i = 0; $i < strlen($string); $i++) {
       
# NOTE: PHP's dereference sucks, we have to do this.
       
$hack = $string{$i};
       
call_user_func($funcname, &$hack, $i, $userdata);
       
$string{$i} = $hack;
    }
}

function
yourFunc($value, $position) {
    echo
$value . ' ';
}

function
yourOtherFunc(&$value, $position) {
   
$value = str_rot13($value);
}

# NOTE: We now need this ugly $x = hack.
string_walk($x = 'interesting', 'yourFunc');
// Ouput: i n t e r e s t i n g

string_walk($x = 'interesting', 'yourOtherFunc');
echo
$x;
// Output: vagrerfgvat
?>

Also note that calling str_rot13() directly on $x would be much faster ;-) just a sample.
up
0
el_porno at web dot de
7 years ago
You want to get rid of the whitespaces users add in your form fields...?
Simply use...:

class SomeVeryImportantClass
{
...
    public function mungeFormData(&$data)
    {
        array_walk($data, array($this, 'munge'));
    }

    private function munge(&$value, &$key)
    {
        if(is_array($value))
        {
            $this->mungeFormData($value);
        }
        else
        {
            $value = trim($value);
        }
    }
...
}

so...
$obj = new SomeVeryImportantClass;
$obj->mungeFormData($_POST);
___
eNc
up
0
Enlightened One
8 years ago
Beware that "array ($this, method)" construct. If you're wanting to alter members of the "$this" object inside "method" you should construct the callback like this:

  $callback[] = &$this;
  $callback[] = method;
  array_walk ($input, $callback);

Creating your callback using the array() method as suggested by "appletalk" results in a copy of $this being passed to method, not the original object, therefor any changes made to the object by method will be lost when array_walk() returns. While you could construct the callback with "array(&$this, method)", I believe this relies on the deprecated runtime pass-by-reference mechanism which may be removed in future releases of PHP. Better to not create a dependence on that feature now than having to track it down and fix it in the future.
up
0
lgaga dot dont dot spam at muszaki dot info
8 years ago
Behaviour like array_walk_recursive() can be achieved in php <=5 by a callback function to array_walk() similar to this:

function walkcallback(&$val,$key) {
    if (is_array($val)) array_walk($val,'walkcallback',$new);
    else {
        // do what you want with $val and $key recursively
    }
}
up
0
paul at heliosville dot com
8 years ago
one rather important note that was lost in the Great PHP Doc Note Purge of '04 is that you can call methods using array_walk(). Let's assume that we have a class named 'Search', in which there is a method called 'convertKeywords'. Here's how you would call that convertKeywords method from inside the class:

    array_walk($keywords, array($this, 'convertKeywords'));

Notice that, instead of giving a string as the second argument, you give an array with two items: the variable that holds the class (in this case, $this), and the method to call. Here's what it would look like if you were to call convertKeywords from an already-instantiated class:

    $search = new Search;
    array_walk($keywords, array($search, 'convertKeywords'));
up
-1
Zigbigidorlu
3 years ago
I tried this function to create safe SQL arrays when I'm creating query strings from keywords, but I found it to be too bulky for my purposes.  So, instead I created this function:

<?php

 
//Create a SQL safe array
 
function mysql_safe_array($array)
 {
   
$array = array();
    foreach(
$array as $item)
    {
       
$safe = mysql_real_escape_string($item);
       
array_push($array,$safe);
        unset(
$safe);
    }
    return
$array;
 }

 
//Example usage
 
$keywords = explode(" ",$_GET['keywords']);

 
$keywords = mysql_safe_array($keywords);

 
$query_s = implode("%' AND `field` LIKE '%",$keywords);
 
$query = "`description` LIKE '%$query_s%'";
 
$query = stripslashes(implode(" ",$query));
?>
up
-1
diyism
4 years ago
Although the manual warned you not to unset element, but sometimes thus is very useful and work as charm:

<?php
$arrChnOut
=array(0=>array('ID' => '13',
                         
'ChannelName' => 'Computers'
                        
),
                
1=>array('ID' => '17',
                         
'ChannelName' => 'Computers'
                        
),
                
2=>array('ID' => '18',
                         
'ChannelName' => 'Computers'
                        
),
                );
array_walk($arrChnOut, create_function('&$v, $k, $arr_rtn', 'if ($k{0}!="_"){$arr_rtn["_".$v[\'ID\']]=$v;unset($arr_rtn[$k]);}'), &$arrChnOut);
var_export($arrChnOut);
?>
up
-1
nihaopaul at nihaopaul dot com
6 years ago
no sure if this should go under array-walk but it does what i need, it searches a multidimensionial array by using an array to walk it, it either returns a value or an array.

<?php
function walker($walk, $array) {
    if (
count($walk) >0) {
        foreach(
$array as $key => $value) {
            if (
$key == $walk[0]) {
                if (
is_array($value)) {
                    unset(
$walk[0]);
                    return
walker(array_values($walk), $value);
                } else {
                    if (isset(
$value)) {
                        if (
count($walk) == 1) {
                            return
$value;
                        } else {
                            return
0;
                        }
                    } else {
                        return
0;
                    }
                }
            }
        }
        return
0;
    } else {
        return
$array;
    }
}
?>
up
-1
thomas dot hebinck at digionline dot de
7 years ago
This is a short way to concatenate a string to each element of an array:

$arr=array(1,2,3,4,5,6,7,8,9,0);
$str=' test'; // must not include ' or " ...

array_walk($arr,create_function('&$elem','$elem .= "' . $str . '";'));

var_export($arr);

The output is:
array ( 0 => '1 test', 1 => '2 test', 2 => '3 test', 3 => '4 test', 4 => '5 test', 5 => '6 test', 6 => '7 test', 7 => '8 test', 8 => '9 test', 9 => '0 test', )
up
-1
caliban at darklock dot com
7 years ago
> I believe this relies on the deprecated runtime
> pass-by-reference mechanism

The array() keyword is a language construct, not a function, so I don't think this is applicable.
up
-2
memandeemail at gmail dot com
8 years ago
If you are using array_walk on a class, dont will work

so ... try this on your own class:

class your_own_class {
    /**
    * @return void
    * @param array $input
    * @param string $funcname
    * @desc A little workaround, do the same thing.
    */
    function array_walk($input, $funcname) {
        foreach ($input as $key => $value) $this->$funcname($value, $key);
    }
}
up
-2
Eierkoek
8 years ago
normaly the $_GET array will add slashes to the array values. To remove all slashes in this array, i created the folowing code

  set_magic_quotes_runtime (0);
  function StripAllSlashes (&$ArrayGET, $Value)
  {
    if (is_array ($ArrayGET)) array_walk ($ArrayGET, "StripAllSlashes");
    else $ArrayGET = stripslashes ($ArrayGET);
  }
  if (isset ($_GET) && get_magic_quotes_gpc ()) array_walk ($_GET, "StripAllSlashes");

I hope this code was usefull,

Eierkoek
up
-3
helloworld at gmail dot com
1 year ago
To retrieve the userData parameter outside the function, you have to pass it by reference inside an array.
<?php
$customData
= array();
$myArray = array('apple', 'orange', 'banana');
array_walk($myArray, 'myFunction', array(&$customData));

function
myFunction(&$item, $index, $data)
{
   
$data[0][$index] = strlen($item);
   
// ...
}

print_r($customData);
?>
Output :
Array ( [0] => 5 [1] => 6 [2] => 6 )

 
show source | credits | stats | sitemap | contact | advertising | mirror sites