Flip the keys with values of an array in Laravel

Created 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

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Buy Me A Coffee

Don't forget to share this article! Help us spread the word by clicking the share button below.

We appreciate your support and are committed to providing you valuable and informative content.

We are thankful for your never ending support.