Currently, you have a multi-dimensional array. You can simpify this approach and flatten your array to one dimension. I suggest you modify your foreach
loop as below:
foreach($first_slice as $key => $value)
{
$arr = explode(' ', trim($value));
$second_slice[$arr[1]] = $arr[0];
}
print_r($second_slice);
Produces the output:
Array
(
[milk] => 5ml
[water] => 5ml
[carrots] => 3pcs
)
Now, to get the quantity for any item, you can directly do echo $second_slice['item_name']
.
And if you wanted to find the name of the quantity from the amount, you can use array_search()
:
$searchFor = '3pcs';
echo array_search($searchFor, $second_slice);
Outputs:
carrots
If there are multiple quantities with the same amount, the above method only returns the first. If you want to get all of them, you can use array_filter()
:
$result = array_filter($second_slice, function($elem) use ($searchFor){
return ($elem == $searchFor);
});
print_r($result);
Output:
Array
(
[milk] => 5ml
[water] => 5ml
)