phparrayscollisionarray-flip

array_flip() causes data loss due to value collisions


The weirdest thing is happening to me...

I have a form I'm sending via an ajax post (using jquery's serialize function) to a php script running this function (stripped down for clarity):

            $arr = $_POST;
            unset($arr['command']);
            unset($arr['index']);
            $vals = $arr;
            $keys = $arr;


            $keys = array_flip($keys);

            return 'vals= ' . implode(',',$vals) . '      keys = ' . implode(',',$keys);

The String I sent that works looks like this...

alt text

that gives me the result...

alt text

now when I Remove the "S" from "About" (in the title field) I get the data string that looks like this: alt text

that gives me THIS result: alt text

The "Title" key has been completely stripped out of the equation!

Any Ideas what could be happening?


Solution

  • While flipping an array if a value has several occurrences, the latest key will be used as its values, and all others will be lost.

    An example(from manual)

    <?php
    $trans = array("a" => 1, "b" => 1, "c" => 2);
    $trans = array_flip($trans);
    print_r($trans);
    ?>
    

    Output:

    Array
    (
        [1] => b
        [2] => c
    )