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
Because
sizes
is an array, your call toarray_column
returns a multi-dimensional array, and so thearray_search
call returnsfalse
as you are trying to compare a string to an array.Probably the simplest way to solve your problem is just to iterate:
Output for your sample data:
Demo on 3v4l.org