1

I have a $products array like this:

Array
(
    [0] => Array
        (
            [0] => 1001
            [1] => 1002
        )

    [1] => 
    [2] => 
    [3] => 
    [4] => 
    [5] => 
    [6] => 
    [7] => 
)

I want to loop through it and create a one-level array comprised only of the non-empty array data like this:

$newArr = [
    [0] => 1001,
    [1] => 1002
]

My foreach loop that I thought would work throws an error ('Invalid argument supplied for foreach()').

The foreach loop looks like this:

$idArr = [];
foreach($products as $value) {
    foreach ($value as $id) {
        echo $id . '<br>';
        $idArr[] = $id;
    }
}

The two values echo suggesting the code is correct, but it's not. I am unable to store the iterated $id value into $idArr[].

If anyone can spot my error or errors, I would appreciate it.

Thanks!

2
  • replace $products with array_filter($products) inside your foreach. Commented Oct 23, 2018 at 19:54
  • 2
    Some of your original array have null elements... not empty arrays... then you must use the second foreach only if $value is not empty... then add if (!empty($value)) { foreach($value as $id){} } Commented Oct 23, 2018 at 19:55

4 Answers 4

1

You don't need to change your code much, you can just skip the inner loop if there's no value.

$idArr = [];
foreach($products as $value) {
    if (!$value) continue;   // continue to next iteration without executing the inner loop
    foreach ($value as $id) {
        $idArr[] = $id;
    }
}

Or enclose the inner loop in an if ($value) ... block. However you like, as long as you're not trying to iterate arrays that aren't there.

Sign up to request clarification or add additional context in comments.

4 Comments

I love your name! Thanks for ending my panic. It works! I found another way here
Thanks :-) Since that other post solves your problem, I think you can flag your own question as a duplicate of it. (I'd prefer not to do that myself since I answered and my vote will close it instantly.)
It's subjective, but I don't think it's a duplicate. In fact, your answer is concise, and therefore, at least in my mind, superior. Brevity wins. In addition, you showed me continue which I never knew. Great and unique answer.
Sure, that's fine, it's up to you. Just wanted to let you know, because most people don't realize it's possible to flag their own posts. I've closed a couple of my own questions after finding good duplicate answers. Many people also view duplicate closures as a negative thing, but it's really not. Your question just becomes a pointer to an answer that already exists.
0
<?php
$arrayTest = [
        'country' => [
            'Russian Federation' => [
                'Region' => [
                    'Moscow',
                    'Moscow',
                    'Moscow'
                ],
                'Moscow', 
                'Moscow', 
                'Moscow'
            ],
            "United States of America" => [
                'Moscow', 
                'Moscow', 
                'Moscow'
            ],
            "China" => [
                'Moscow', 
                'Moscow', 
                'Moscow'
            ]
        ],

        'union' => [
            'Moscow', 
            'Moscow'
        ], 

        'status' => 1, 

        'age' => 34
    ];

$result = [];
array_walk_recursive($arrayTest, function ($item, $key) use (&$result) {
    $result[] = $item;    
});
print_r($result);
?>

Comments

0

You could use PHP Spl RecursiveIteratorIterator

$array = array(1,2,array(3,4, array(5,6,7), 8),[0=>1, 1=> [0=>null]], 9);
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($a));
foreach($it as $v) {
  echo $v, " ";
}

prints

1 2 3 4 5 6 7 8 1 9

reference modified to suit your example

Comments

0
$idArr = array();
foreach($products as $value) {
    if(is_array($value)){
        foreach ($value as $id) {
                $idArr[] = $id;
         }
      }
 }

4 Comments

$value from first foreach loop is array so I didn’t understand why second foreach is wrong
print_r([[], null]) is your friend here.
P.S. Now your if(count($value)>0){ solution is not a solution at all, please study print_r output first.
P.P.S. Now your if($id!=null) is not required anymore.

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.