Debug School

rakesh kumar
rakesh kumar

Posted on

How to use array_keys and array_flip in Laravel

array_keys:
The array_keys function is used to retrieve all the keys from an associative array or a list.

Example:

$fruits = array(
    'apple' => 2,
    'banana' => 5,
    'orange' => 3,
    'kiwi' => 1
);
Enter fullscreen mode Exit fullscreen mode
$fruitNames = array_keys($fruits);

print_r($fruitNames);
Enter fullscreen mode Exit fullscreen mode

In this example, array_keys($fruits) extracts all the keys from the associative array $fruits. The output will be:

Array
(
    [0] => apple
    [1] => banana
    [2] => orange
    [3] => kiwi
)
Enter fullscreen mode Exit fullscreen mode

array_flip:
The array_flip function is used to exchange the keys and values of an array. Note that for the flip to be successful, the values must be unique.

Example:

$fruits = array(
    'apple' => 2,
    'banana' => 5,
    'orange' => 3,
    'kiwi' => 1
);
Enter fullscreen mode Exit fullscreen mode
$flippedFruits = array_flip($fruits);

print_r($flippedFruits);
Enter fullscreen mode Exit fullscreen mode

In this example, array_flip($fruits) exchanges the keys and values in the associative array $fruits. The output will be:

Array
(
    [2] => apple
    [5] => banana
    [3] => orange
    [1] => kiwi
)
Enter fullscreen mode Exit fullscreen mode

Combined Example:
Now, let's combine array_keys and array_flip:

$fruits = array(
    'apple' => 2,
    'banana' => 5,
    'orange' => 3,
    'kiwi' => 1
);
Enter fullscreen mode Exit fullscreen mode
$fruitNames = array_keys($fruits);
$flippedFruits = array_flip($fruitNames);

print_r($flippedFruits);
Enter fullscreen mode Exit fullscreen mode

Here, array_keys($fruits) gets the keys from the original array, and then array_flip flips them back. The result will be the original array:

Array
(
    [apple] => 2
    [banana] => 5
    [orange] => 3
    [kiwi] => 1
)
Enter fullscreen mode Exit fullscreen mode

One Practical Example

my request data coming from fron end

[2024-01-05 07:46:06] local.INFO: array (
  '_token' => 'JEQba4vUNZ5LP1Jz7eaI9JAwblbOAf7S8EO6i14C',
  'face_price' => '24',
  'youtube_price' => '69',
  'admin_id' => '26',
  'slug' => 'admins',
  'influencer_email' => 'admins@gmail.com',
  'influencer_admin_id' => NULL,
  'org_name' => NULL,
  'admin_email' => 'rakeshdev.cotocus@gmail.com',
  'user_name' => 'rakeshdev',
  'slug_id' => NULL,
) 
Enter fullscreen mode Exit fullscreen mode
$data= Addprofile::where('user_email',$inf_email)->first(); 
Enter fullscreen mode Exit fullscreen mode

following below code The code will update the 'addcarts' column in the 'addprofiles' table, create a new 'addcart' instance, and update the pricing information for the selected social media platforms before saving it to the database.

 if($data) 
                    {                        
                     $addingprofile= DB::table("addprofiles")->where('id',$itemId)->update(['addcarts' => "$admins_email:yes"]);
                     Log::info("addprofile cart id hain na"); 
                     $selectedSocials = array_keys($request->all()); 
                     $selectedSocialsKeys = array_keys(array_flip($selectedSocials));
                     Log::info('Selected Socials:', ['selectedSocials' => $selectedSocialsKeys]);                   
                     $socialSites = ['face_price','twitter_price','youtube_price', 'wordpress_price', 'tumblr_price','instagram_price','quora_price', 'pintrest_price','reddit_price','koo_price','scoopit_price','slashdot_price', 'telegram_price','linkedin_price'];                     
                         $addCart = new addcart;
                         $addCart->admin_id =$request->admin_id;
                         $addCart->cart_id = $cartID;
                         $addCart->influencer_admin_id = $influencer_admin_id;
                         $addCart->admin_email = $admins_email;
                         $addCart->user_name = $request->user_name;
                         $addCart->slug = $request->user_name;
                         $addCart->influencer_email = $request->influencer_email; 
                         foreach ($socialSites as $socialSite) {
                            Log::info("socialSites cart id hain na");
                             // Check if the social site is in $selectedSocials
                             if (in_array($socialSite, $selectedSocialsKeys)) {
                                Log::info("in_array cart id hain na");
                                 // Update the property of the existing $addCart instance
                                 $addCart->{$socialSite} = $payments->{$socialSite} ?? 0;
                             }
                         }                      
                         $addCart->save();
Enter fullscreen mode Exit fullscreen mode

output

Image description

Explanation

$selectedSocials: It gets all the keys (names) from the associative array obtained from $request->all(). In this case, it's likely fetching the names of selected social media platforms from a form submission.

array_flip($selectedSocials): It flips the keys and values of the array, making the current keys (social media platform names) become values and vice versa.

array_keys(...): Finally, it retrieves the keys from the flipped array, resulting in an array with the original keys (social media platform names). This step is useful to ensure that the array contains unique values.

Top comments (0)