Remove array keys and values if it does not exist in other array in Laravel

Updated at 21-May-2021, By samar

Remove array keys and values if it does not exist in other array in Laravel

In this session, we’ll try our hand at solving the "Remove array keys and values if it does not exist in other array in Laravel" puzzle by using the computer language.

Laravel provides an array helper method to get the keys and values from the array which is specified by another array. In this way you can remove array keys and values if it does not exist in another array.
  • Laravel array_only helper method

    $allArrayItems = array('175' => 20, '179' => 30, '181' => 80);
    $arrayItemsToGet = array( '0' => 175, '1' => 179);
    $arrayItems = array_only($allArrayItems, $arrayItemsToGet);
    print_r($arrayItems);
    
    //Another method: 
    //Use can pass keys as index key (second parameter values)
    $allArrayItems = array('175' => 20, '179' => 30, '181' => 80);
    $arrayItemsToGet = array('175', '179');
    $arrayItems = array_only($allArrayItems, $arrayItemsToGet);
    print_r($arrayItems);
    

    //Output

    Array passed as first argument: Array ( [175] => 20 [179] => 30 [181] => 80 )
    Array passed as second argument: Array ( [0] => 175 [1] => 179 )
    Output return by function: Array ( [175] => 20 [179] => 30 )

    Method array_only() is the helper method in Laravel which returns only the specified key-value pair from the array.

    The array_only() method will remove all other keys and values from the array (from the first argument) if it does not exist in another array using keys which is passed as a second argument to this method. You have to pass the keys in array form as the second argument which you want to get from the existing array. 

Back to code snippet queries related laravel