0

Say I have the following array of associative arrays:

$MasterArr = array(
    array("food" => "apple", "taste" => "sweet"),
    array("food" => "lemon", "taste" => "sour"),
    array("food" => "steak", "taste" => "meaty")
);

Without using a foreach loop, is there a way that can I "chop" it into 2 different arrays whose values come from the same keys, so it looks like this:

$FoodArr = array("apple","lemon","steak");
$TasteArr = array("sweet","sour","meaty");
4
  • Just to say: At the end you will always loop through your array. If you now see it in your written code or not. Commented Jul 28, 2016 at 21:31
  • @Nitin I like to minimize lines of code where I can, so I had a feeling there was some 1-liner way to do this Commented Jul 28, 2016 at 21:33
  • implemetation of array_column Commented Jul 28, 2016 at 21:34
  • @user3163495 Did not know that array_column() is faster than foreach. stackoverflow.com/questions/35319318/… Commented Jul 28, 2016 at 21:41

2 Answers 2

4

You can use array_column for that:

$FoodArr = array_column($MasterArr, 'food');
$TasteArr = array_column($MasterArr, 'taste');
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I fixed the typo in the question. I'll mark this as answer after 10 mins (SO making me wait)
3

For PHP < 5.5.0, you can use array_map:

$FoodArr = array_map(function($v){ return $v['food']; }, $MasterArr);
$TasteArr = array_map(function($v){ return $v['taste']; }, $MasterArr);

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.