Search code examples
phparraysrebuild

Php array rebuild


I got an array looking like this:

array("canv" => array(1 => "4", 2 => "6", 3 => "9", 4 => "7");

I need it to look like this:

array("canv" => array("4", "6", "9", "7");

so I can easly check if the value exist this way:

if(isset($result["canv"][$gid])) where $gid is a number from "4", "6", "9", "7".

How can it be done?


Solution

  • This will flip the values to become keys and vice versa:

    $result["canv"] = array_flip($result["canv"]);
    

    So instead of

    array(1 => "4", 2 => "6", 3 => "9", 4 => "7")
    

    you'll have

    array("4" => 1, "6" => 2, "9" => 3, "7" => 4)
    

    But then again think about building the original array in the desired way and only do this if you can't afford that.