0

All. I am sure that someone may have asked similar thing but I failed to find the related thread. I have the following array of associative array

May I know how I can extract an array of data with only [type] => Beverage ?

Array ( 
    [0] => Array ( 
        [id] => 1 
        [prod_name] => Coffee 
        [type] => Beverage 
    ) 
    [1] => Array ( 
        [id] => 2 
        [prod_name] => Vegetable 
        [type] => Food 
    )
    [2] => Array ( 
        [id] => 3 
        [prod_name] => Orange Juice 
        [type] => Beverage 
    )
)

I have looked at the function array filter but still cannot figure the answer out. Thanks.

0

1 Answer 1

1

You can do this easily with array_filter:

$data = [
    ['id' => 1, 'prod_name' => 'Coffee', 'type' => 'Beverage'],
    ['id' => 2, 'prod_name' => 'Vegetables', 'type' => 'Food'],
    ['id' => 3, 'prod_name' => 'Orange Juice', 'type' => 'Beverage'],
];

$output = array_filter($data, function ($record) {
    if ($record['type'] == 'Beverage')
        return $record;
});

var_dump($output);

Yields:

array(2) {
  [0]=>
  array(3) {
    ["id"]=>
    int(1)
    ["prod_name"]=>
    string(6) "Coffee"
    ["type"]=>
    string(8) "Beverage"
  }
  [2]=>
  array(3) {
    ["id"]=>
    int(3)
    ["prod_name"]=>
    string(12) "Orange Juice"
    ["type"]=>
    string(8) "Beverage"
  }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Just return $record['type'] == 'Beverage' would do. "If the callback function returns true, thecurrent value from array is returned into the result array." The modern short version for a one-op filter would be, $output = array_filter($data, fn($record) => $record['type'] == 'Beverage');.
Indeed it could be more terse, I think the more verbose syntax is good for somebody learning to understand.
That it is, just dropped in the option. Still, on the return value, array_filter only cares about a boolean. A strict comparison of $record['type'] === 'Beverage' is true. Any string value is "truish" and will simply be coerced to true. No need for that.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.