array_flip

  • This function’s solution uses a Ruby Hash object since Ruby arrays don’t use associative key/value pairs. See Array for more details.

    We can swap key/values in a Ruby hash using Hash#invert.

    PHP

    $array = array('bike' => 1, 'car' => 2, 'truck' => 3);
    $result = array_flip($array);
    var_export($result);
    // => array(1 => 'bike', 2 => 'car', 3 => 'truck')

    Ruby

    hash = {'bike' => 1, 'car' => 2, 'truck' => 3}
    p hash.invert
    # => {1 => "bike", 2 => "car", 3 => "truck"}

    Just like in PHP, conflicting keys will be overwritten.

    PHP

    $array = array('bike' => 1, 'car' => 1, 'truck' => 2);
    $result = array_flip($array);
    var_export($result);
    // => array(1 => 'car', 2 => 'truck')

    Ruby

    hash = {'bike' => 1, 'car' => 1, 'truck' => 2}
    p hash.invert
    # => {1 => "car", 2 => "truck"}

    see also

Looking for Rails or PHP web application development, integration, and training?

Rails for PHP is brought to you by Maintainable Software. Get custom web applications and personalized training from the authors of the book and website.