0

How can i create an associative array using the array below, In the fastest and shortest way.

$list = array(array('name', 'aram'), array('family', 'alipoor'));

Something like:

$list = array('name' => 'aram', 'family' => 'alipoor');
3
  • Is is safe to assume that you're not running into any speed issues anyway? And additionally: How do you measure fastest and shortest? Isn't the fastest always the shortest? Or is shortest the number of characters the code consists of? Commented Aug 22, 2011 at 12:29
  • In my situation fastest means fastest to write (characters) and speed is not that important. Commented Aug 22, 2011 at 12:43
  • Keep in mind that code is far more often read than written, so if you're open for a suggestion, you should more take care that code is easy (fast) to read, not fast to type. Commented Aug 22, 2011 at 12:45

4 Answers 4

2

The shortest I can think of:

$newlist = array();
foreach ( $list as $keyval ) {
    $newlist[ $keyval[0] ] = $keyval[1];
}
Sign up to request clarification or add additional context in comments.

2 Comments

It will be shortest if there wasn't any loops. Isn't there any way to do it in one single line using php functions
Is the initial array of defined length? Otherwise you have to have a loop.
2
$assocArray = array();

foreach($list as $subArray)
{
    $assocArray[$subArray[0]] = $subArray[1];
}

Comments

0

Terrible approach, but

$lst = array_combine(array_map('array_shift',$list), array_map('array_pop',$list));

Works only for two-element inner arrays.

Note: three implicit loops in this solution. So better use approach from Rijk van Wel or kevinmajor1 answer

Comments

0

I generally think foreach is pretty well readable and normally pretty fast. If you want it in one line, you can do with foreach as well:

$nl = array(); foreach($list as $k=>$v) $nl[$k]=$v; $list = $nl; unset($nl);

Which is basically demonstrating that there is no value in getting something "single line".

Or if you prefer callbacks for some reason I don't know of:

$list = array_reduce($list, function($v,$w) {return $v+array($w[0]=>$w[1]);}, array());

Which demonstrates that as well. It will hardly be faster than foreach, in any case, the speed differences most certainly do not matter in your case.

Comments