PHP – convert array to associative array

Convert using array_flip()

This works if we need index as value.

<?php
$a = array("foo", "bar");
$aa = array_flip($a);
print_r($aa);
?>
Array
(
    [foo] => 0
    [bar] => 1
)
Env: PHP 5.5.9 (Linux)

Using foreach iterator

In case we need to set associative array value using array index and or value.

<?php
$a = array("foo", "bar");
$aa = array();
foreach ($a as $idx => $val) {
  $aa[$val] = $idx + 1;
}
print_r($aa);
?>
Array
(
    [foo] => 1
    [bar] => 2
)
Env: PHP 5.5.9 (Linux)

Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments