2

Let's say I have this array:

array(12) {
  [0] =>
  array(0) {
  }
  // [...]
  [9] =>
  string(5) "test"
  [10] =>
  array(0) {
  }
  [11] =>
  class stdClass#5 (0) {
  }
}

All items in this array where added like this $a[] = $somevalue.

Now I add another item: $a[] = new Foobar('bar');

However this results in:

array(13) {
  [0] =>
  array(0) {
  }
  // [...]
  [9] =>
  string(5) "test"
  [10] =>
  array(0) {
  }
  [11] =>
  class stdClass#5 (0) {
  }
  [21] =>
  class Foobar#8 (3) {
    protected $id =>
    string(11) "bar"
  }
}

My Foobar object is not $a[12], why? Is there anything I can do such that PHP iterates properly?

Update: I was not able to reproduce this behaviour in a single file. Unfortunately, a whole framework is involved in my code. As I'm only in control of the last statement ($a[] = new Foobar('id');), can I do something before that expression to force PHP to iterate properly?

3
  • Cannot reproduce. Are you sure you're not setting & unsetting 12-20? Commented Feb 22, 2015 at 14:57
  • 1
    Please show us your full code! Commented Feb 22, 2015 at 14:59
  • @kingkero The items might be set & unset, is there any way I can reset the counter? Commented Feb 22, 2015 at 15:04

1 Answer 1

1

I'm not sure if you mean this, but here it goes: PHP arrays do not have to be indexed in the standard way; If you unset 12-20, the last item (namely 21 will not have its index changed). You can also have strings as keys; it's more like a key-value pair than a standard table you might find in other languages. You can use foreach to iterate over an array.

$a = array(
  0 => 2,
  21 => 30,
  "foo" => "bar"
);

foreach ($a as $val)
{
    echo $val;
    echo "\n";
}

will print:

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

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.