skip to Main Content

I have an array that contains some keys and one additional nested array. I’m trying to figure out how to check if a specific value exists within the nested array, and if so, get another value from the parent array. Here’s an example of my array:

$products = array(
    array(
        'product_name' => 'My First Product',
        'price' => 50,
        'sizes' => [
            'S',
            'L',
            'XL'
        ]
    ),
    array(
        'product_name' => 'My Second Product',
        'price' => 45,
        'sizes' => [
            'S',
            'M',
            'L',
            'XL'
        ]
    )
)

In this example I would like to search the array to see if a product with size M exists and, if so, get the product_name. I believe I can do this with a combination of array_search and array_column but thus far have been unsuccessful.

Here is what I attempted:

$col = array_search('M', array_column($products, 'sizes'));
$productName = $products[$col]['product_name'];

This does give me a result, but it returns My First Product, even though that product doesn’t have size M. I’m sure this has been answered before, but unfortunately I’m not quite sure what the terminology is for what I’m attempting to do here so I haven’t been able to find an answer.

2

Answers


  1. Because sizes is an array, your call to array_column returns a multi-dimensional array, and so the array_search call returns false as you are trying to compare a string to an array.

    Probably the simplest way to solve your problem is just to iterate:

    $productNames = array();
    foreach ($products as $product) {
        if (in_array('M', $product['sizes'])) $productNames[] = $product['product_name'];
    }
    print_r($productNames);
    

    Output for your sample data:

    Array
    (
        [0] => My Second Product
    )
    

    Demo on 3v4l.org

    Login or Signup to reply.
  2. $result = array_filter($products, fn($item) => in_array('M', $item['sizes']));
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search