1

Is there anyway that an indexed array say ['1' => 'dave, '2' => 'ryan', '3' => 'mike', '4' => 'sam'] can be turned into an associative array. Which in this case would be ['dave' => 'ryan', 'mike' => 'sam'].

Obviously in the context and with the example i've given it doesn't make much sense but it would be helpful would just be handy to know.

All I can find on Google or here is ways of doing the opposite (associative -> indexed) unless I am completely missing an obvious answer.

Joe Lencioni
  • 10,231
  • 18
  • 55
  • 66
RyanM
  • 53
  • 4

2 Answers2

1
$array = array('1' => 'dave', '2' => 'ryan', '3' => 'mike', '4' => 'sam');
$result = array();
for($i = 1; $i <= count($array); $i += 2) {
  $result[$array[$i]] = $array[$i+1];
}

Output

var_dump($result);
array(2) {
  ["dave"]=>
  string(4) "ryan"
  ["mike"]=>
  string(3) "sam"
}
Dogbert
  • 212,659
  • 41
  • 396
  • 397
1

This is the simplest way that I can think of for your example:

$arr = array('1' => 'dave', '2' => 'ryan', '3' => 'mike', '4' => 'sam');
$result = array();
$key = null;

foreach(array_keys($arr) as $k) {
    $v = $arr[$k];

    if($key === null) {
        $key = $v;
    } else {
        $result[$key] = $v;
        $key = null;
    }
}

Here's a demo.

Ry-
  • 218,210
  • 55
  • 464
  • 476