0

I'm trying to remove arrays in the cars array if the make value belongs in the retiredCars array. I did run into array_search but I'm not sure how to apply it to a multi dimensional array

$retiredCars = array("Saab", "Saturn", "Pontiac");

$cars = array
  (
  array('make' => 'BMW', 'model' => '325'),
  array('make' => 'Saab', 'model' => '93'),
  array('make' => 'Pontiac', 'model' => 'GTO')
  );

In the example above, the $cars array should only contain the 'BMW' array after processing

LF00
  • 27,015
  • 29
  • 156
  • 295
Arya
  • 8,473
  • 27
  • 105
  • 175

4 Answers4

1
foreach ($cars as $key => $arr) {
    if (in_array($arr['make'], $retiredCars))
        unset($cars[$key]);
}
ES112
  • 91
  • 4
  • 1
    Hi, code-only answers might solve the problem, but they are way less valuable to further readers, than an answer, that also contains some explaination. Therefore it would be highly appreciated, if you could expand your answer to include some explaination. – derM - not here for BOT dreams May 10 '17 at 11:13
0

Unsetting array's elements while iterating over it doesn't seem a good approach. Another idea:

$array_elem_passes = function ($val) use ($retiredCars)
{
        if (in_array($val['make'], $retiredCars))
                return false;

        return true;
};

$ret = array_filter($cars, $array_elem_passes);  
KotBehemot
  • 111
  • 8
  • It looks like the perfect approach to me in this case. Your way will be much slower. Can you explain why you think differently? – ES112 May 13 '17 at 12:43
  • I think that, as a general rule, modifying an array while you're iterating on it isn't something that should be encouraged as it potentially can cause unwanted behaviour. – KotBehemot May 15 '17 at 08:43
0

You can use array_filter, for performance flip the retiredCars array. Live demo

You also can use array_udiff to make it. Refer to this post.

<?php
$retiredCars = array("Saab", "Saturn", "Pontiac");

$cars = array
  (
  array('make' => 'BMW', 'model' => '325'),
  array('make' => 'Saab', 'model' => '93'),
  array('make' => 'Pontiac', 'model' => 'GTO')
  );

$makes = array_flip(array_unique($retiredCars));
print_r(array_filter($cars, function($v)use($makes){return isset($makes[$v['make']]);}));
Community
  • 1
  • 1
LF00
  • 27,015
  • 29
  • 156
  • 295
0

Yes. array_udiff do the trick in this way

$res = array_udiff($cars, $retiredCars, 
     function($c, $r) { 
         // You need test both variable because udiff function compare them in all combinations
         $a = is_array($c) ? $c['make'] : $c;
         $b = is_array($r) ? $r['make'] : $r;
         return strcmp($a, $b); 
         });

print_r($res);

demo on eval.in

splash58
  • 26,043
  • 3
  • 22
  • 34