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.

1
  • 2
    All arrays in PHP are associative. It's just that sometimes, the key is a linearly increasing integer sequence... Commented Mar 18, 2012 at 15:48

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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"
}

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.