NYCPHP Meetup

NYPHP.org

[nycphp-talk] efficient array manipulation

Dan Cech dcech at phpwerx.net
Thu Apr 28 18:49:44 EDT 2005


Tom,

Here's a one-liner that will do what you want:

array_walk($myarr,create_function('&$v','array_walk($v,create_function(\'&$v\',\'$v 
= array(\\\'element1\\\'=>$v,\\\'element2\\\'=>\\\'myval\\\');\'));'));

For maintainability (and speed) I would probably use something a little 
more readable though:

function callback(&$v)
{
   $v = array(
     'element1' => $v,
     'element2' => 'myval'
   );
}

array_walk($myarr,create_function('&$v','array_walk($v,\'callback\');'));

or the old foreach loop:

foreach ($myarr as $k => $v) {
   foreach ($v as $k2 => $v2) {
     $myarr[$k][$k2] = array(
       'element1' => $v2,
       'element2' => 'myval'
     );
   }
}

My testing indicates the for small arrays the foreach loop is marginally 
faster, but when the loop grows the second array_walk is actually the 
fastest (the one-liner gets left in the dust because it has to recreate 
the second callback function for every iteration of the outer loop).

Dan

Tom Melendez wrote:
> Hey Folks,
> 
> Say I have a two-dimensional array with 5000 items in it.
> 
> I need to turn an array that looks like this:
> 
> $myarray[0][0]="foo";
> 
> into
> 
> $myarray[0][0][element1]=foo (the value of the original $myarray[0][0])
> $myarray[0][0][element2]=some_value_that_never_changes
> 
> I'm looking for the most efficient way possible to do this.  I really 
> don't want to use a loop, I'm looking at array_walk now, but I'm hoping 
> there is a "one or two liner" that is efficient and easy.
> 
> Any thoughts?
> 
> Thanks,
> 
> Tom
> http://www.liphp.org



More information about the talk mailing list