Flip the keys with values of an array in Laravel

Updated at 26-Aug-2022, By samar

Flip the keys with values of an array in Laravel

In this session, we will try our hand at solving the "Flip the keys with values of an array in Laravel".

Flip method sets the key as value and value as key in the collection array in Laravel. Flip method swaps the Laravel collection's keys with their corresponding values. Like, if we have the key with name website and the value with data w3codegenerator and if we want to set the w3codegenerator as key and website as value then flip method is helpful.
  • Call flip method on array in Laravel

    $array = ['website' => 'w3codegenerator', 'framework' => 'laravel'];
    $results =  collect($array);
    
    $flipped = $results->flip();
    $flipped->all();
    
  • Laravel flip method on collection

    $collection = collect(['website' => 'w3codegenerator', 'framework' => 'laravel']);
    $flipped = $collection->flip();
    $flipped->all();
    

    Output:

    lluminate\Support\Collection Object ( [items:protected] => Array ( [w3codegenerator] => website [laravel] => framework ) [escapeWhenCastingToString:protected] => )

Back to code snippet queries related laravel