Ruud
Ruud

Reputation: 65

Foreach returns one item to much

I have something that I can't get my head around:

I am processing an array with a foreach loop. The array has 3 items. I do some stuff with these items which are stored back into a different array. After the foreach loop I have not 3 but 4 items in the array... I checked every part of the process with var_dump and print_r to check if there is a "hidden" item that causes this behavior, but I can't find it.

The result of a Query is turned into a array, the result set is 3 rows. Here is an example of the code:

 echo sizeOf($arrWithItems);  //returns 3
 $i=0;
 $newArrWithItems = array();

 foreach($arrWithItems as $item){
        $i++; //add one to the counter (only for testing)

        // do stuff with $item for example:
        $newArrWithItems[$item->id]['name'] = $item->name;
 }

 echo sizeOf($newArrWithItems) //returns 4
 echo $i   //returns 3

The weird thing is that when I echo the sizeOf($newArrWithItems) within the foreach loop, it start with 0, and goes further with 2 and 3. So it skips 1. But the count ($i) doesn't skip a step.

What do I miss here... or are there any tips howto debug is further? I already checked the $arrWithItems with var_dump, it shows only 3 items, nicely number from 0 to 2. To problem doesn't occure only with this result set, but it addeds one item to all the arrays that are processed in this foreach loop.

Upvotes: 0

Views: 162

Answers (4)

f.1
f.1

Reputation: 1

It's not clear whether $arrWithItems is ArrayObject or just array? If that is the array, here is the simple example:

$arrWithItems = array(
    array("id"      => 1,
        "name"      => "Jack",
        "address"   => "Columbus",
        "age"       => 25),

    array("id"      => 3,
        "name"      => "Hyam",
        "address"   => "Wyan",
        "age"       => 26),

    array("id"      => 10,
        "name"      => "Jenny",
        "address"   => "Norfolk",
        "age"       => 25),
);

$newArrWithItems = array();

foreach($arrWithItems as $key=>$item){
    // do stuff with $item for example:
    $id = $item['id'];
    $newArrWithItems["$id"]["name"] = $item['name'];
}
echo sizeOf($newArrWithItems); //returns 3

Upvotes: 0

Ruud
Ruud

Reputation: 65

after comparing it again with var_dump I found the mistake. It was indeed something in the "do stuff with $item" where the [$item->id] was not set in the New Arr.

Upvotes: 0

Peter de Groot
Peter de Groot

Reputation: 829

Are you sure that $newArrWithItems is empty before you start the foreach loop? May be you can add this to your code just before 'foreach':

$newArrWithItems = array();

Upvotes: 0

Yash
Yash

Reputation: 1436

put this before foreach loop:

 $newArrWithItems = array();

I tried and it shown result as 3.

Upvotes: 1

Related Questions