Search code examples
phparrayssequentialassociative

PHP Transform mixed sequential and associative array to associative array


I would like to build $goal array from $initial only. Any ideas? Thank you

Edit : the question could be how to differentiate associative parts from sequential ones.

$intial=[
    "one",
    "two"=>"myTwo",
    "three",
    "four"=>"myFour"
];
$goal=[
    "one"=>null,
    "two"=>"myTwo",
    "three"=>null,
    "four"=>"myFour"
];

Solution

  • The 'sequential' parts will have numeric keys, so if your 'associative' keys will always be strings, you could use that to differentiate:

    $goal = [];
    foreach ($initial as $key => $value) {
        if (is_numeric($key)) {
            $goal[$value] = null;
        } else {
            $goal[$key] = $value;
        }
    }