phparraysfilteringarray-intersect

Filter flat array by values in another flat array


I have an array as follows:

$aq = ['jonathan', 'paul', 'andy', 'rachel'];

Then I have an array as follows:

$bq = ['rachel', 'andy', 'jonathan'];

What I need is to use the second array to filter the first array.

So for this instance, the resulting array should be:

$cq = ['jonathan', 'andy', 'rachel'];

I started working on a solution that uses the highest key as the top value (the head of the array) because what I'm looking for is the top value but that ran into issues and seemed more like a hack.

Is there a simple function in php that can sort my data based on my first array and there respective positions in the array?


Solution

  • please try this short and clean solution using array_intersect:

    $aq = ['jonathan','paul','andy','rachel'];
    
    $bq = ['rachel','andy','jonathan'];
    
    $cq = array_intersect($aq, $bq);
    
    var_export($cq);
    

    the output will be :

    array ( 0 => 'jonathan', 2 => 'andy', 3 => 'rachel', )