5

I have a simple array where key is always followed by the value:

Array (
    [0] => x
    [1] => foo
    [2] => y
    [3] => bar
)

which I would like to convert to associative one:

Array (
    [x] => foo
    [y] => bar
)

What is the easiest and most elegant way to do this?

8 Answers 8

5

To be memory efficient, and less calculations.

If the $input array has odd number of values, the last value will be NULL.

$result = array();

while (count($input)) {
    $result[array_shift($input)] = array_shift($input);
}
Sign up to request clarification or add additional context in comments.

Comments

2

I don't know how efficient this is, but:

$newArray = array();
foreach(array_chunk($array, 2) as $keyVal){
    list($key, $val) = $keyVal;
    $newArray[$key] = $val;
}

DEMO: http://codepad.org/VF8qHAhQ

Comments

2
$ar = Array("x","foo","y","bar");

$assoc = Array();

for($i=0;$i<count($ar);$i+=2){$assoc[$ar[$i]]=$ar[$i+1];}

print_r($assoc);

Output: Array ( [x] => foo [y] => bar )

Comments

1

I'll start it off with a simple for loop

$arr = array(
'x',
'foo',
'y',
'bar'
);

$result = array();
$end = count($arr);
for ($i = 0; $i+1 < $end; $i+=2) {
  $result[$arr[$i]] = $arr[$i+1];
}

var_dump($result);

Output:

array(2) {
  ["x"]=> string(3) "foo"
  ["y"]=> string(3) "bar"
}

1 Comment

Errata should note that this assumes that the key is always followed by the value.
1

Assuming you want the key/value pairs to be in the every/other pattern, you could use:

$data = array('x', 'foo', 'y', 'bar', 'z');
$new = array();

$end = count($data);
for ($i = 0; $i < $end; $i += 2) {
    $new[$data[$i]] = (isset($data[$i + 1]) ? $data[$i + 1] : '');
}

print_r($new);

Will give:

Array
(
    [x] => foo
    [y] => bar
    [z] => 
)

This will iterate through your list of data and set the first value as the key and the next as the value. If there is no "next" value (i.e. - the final item in the original array that isn't divisible by 2), it's empty.

The caveat to this approach is that if the same "key" is seen more than once it will be overwritten. This could be circumvented with the addition of if (isset($new[$data[$i]])) continue; as the first line in the loop.

Comments

1

How about:

$data = array('x','foo','y','bar');
$i = 0;
$n = count($data)
$newData = array();
while($i < $n) {
    $newData[$data[$i]] = $data[++$i];
}

Comments

0

The modern equivalent of @Rocket's snippet is to employ array de-structuring in the foreach() loop.

My snippet does not use a "counter" variable or make any iterated function calls.

This will be very efficient as there is only ever 1 function call to generate the desired result.

Code: (Demo)

$array = ['x', 'foo', 'y', 'bar', 'z', 'zed'];

$result = [];
foreach (array_chunk($array, 2) as [$k, $v]) {
    $result[$k] = $v;
}
var_export($result);

Output:

array (
  'x' => 'foo',
  'y' => 'bar',
  'z' => 'zed',
)

Comments

0

So the value of the key are in following order that when we place a key for a value so we don't need that index.I assume the given array's key is always integer and start from 0.

$array = ['x', 'foo', 'y', 'bar', 'z', 'zed'];
var_dump( $array);
$new = [];
foreach ($array as $key => $value) {
      if( ($key % 2) === 1 )
         $new[ $array [ $key-1 ] ] = $value;
      
}

 var_dump( $new ); 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.