1

I have an array of objects, where each object contains an array for an attribute

$cars = [
    "toyota" => ["colors" => ["red","blue"]],
    "mazda" => ["colors" => ["red"]],
    "honda" => ["colors" => ["blue"]],
    "nissan" => ["colors" => ["red","yellow"]],
];

I need a function that will return all the cars that have a specified color.

I can do this using a foreach loop.

function getCarsByColor(string $color, array $cars){
    foreach($cars as $key => $car){
        if(!in_array($color, $car['colors'])){
          unset($cars[$key]);
        }
    }

    return $cars;
}

Just wondering if there's a more direct way of doing this.

Thanks.

4
  • 1
    Do you get the data from mysql? If so you could do it in your query Commented Mar 7, 2019 at 17:13
  • That's a good point. It's actually Postgres. The cars object is stored inside another object, as jsonb, so how would filter this out when querying for it? Commented Mar 7, 2019 at 17:18
  • something like Select car.name, color.name from car inner join color on color.idCar = car.id where color = 'yourColorByPreparedStatementHere' Commented Mar 7, 2019 at 17:24
  • I don't think I can run that query on a jsonb. If the car attributes were stored in their columns then it would work Commented Mar 7, 2019 at 17:41

2 Answers 2

2

This approach uses array_filter()

$red_cars = array_filter($cars, function($car) {
    return in_array('red', $car['colors']);
});

As a function

function get_cars_by_color(array $cars, string $color = '') {
    return array_filter($cars, function($car) use ($color) {
        return in_array($color, $car['colors']);
    });

}

use() passes a variable from the current scope into a closure functions scope.

Sign up to request clarification or add additional context in comments.

Comments

0

There's nothing conceptually wrong with what you're doing. In this specific scenario, really your only two choices are 1) modify the array copy to remove unwanted entries (what you're doing now), or 2) create a new array with only-wanted entries. Take your pick, really. One thing I do notice:

if(!in_array($color, $car['color'])){

This might be a typo but based on your array definition there will be no index named 'color'.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.