roman
roman

Reputation: 525

Can't access array by index, but can iterate with foreach

How come that I can't access array by index $obj->property[0] but can iterate through the array (each has only one value) and then get the value.

foreach($obj->property as $inner_obj)
{
    foreach($inner_obj->property as $inner_inner_obj)
        echo $inner_inner_obj->property;
}

If I access array by index I get Undefined offset: 0

Edit: Output of var_dump

array(1) {
 [0]=> object(FooClass)#141 {
   // yadda yadda
  }
}

Upvotes: 0

Views: 1553

Answers (4)

Kovge
Kovge

Reputation: 2019

The $obj->property could be an array without having key 0. The keys in your array might not be numeric. So your array might be an associative array not a regular. If you want numeric indexing try this:

  $numArray = array_values($obj->property);
  var_dump($numArray);

If you want to access the first value of an array use:

  $first = reset($obj->property);

It works if your variable is an array.

Upvotes: 0

mohammad mohsenipur
mohammad mohsenipur

Reputation: 3149

if you make class by implements Countable, Iterator you can make a object that work with foreach but it is not array

Upvotes: 1

Anyone
Anyone

Reputation: 2835

Because you're looping over properties of an array in a foreach. With [0] you explicitly try to access it as an array. You can have your object extend ArrayObject and make php access your object as an array which is what you want I think.

The interfaces that gives the ability to use your object as an array:
http://www.php.net/manual/en/class.arrayaccess.php
http://www.php.net/manual/en/class.countable.php
http://www.php.net/manual/en/class.iteratoraggregate.php

The object itself which you can extend:
http://www.php.net/manual/en/class.arrayobject.php

Imo, it's never a good idea to loop over an object without array interface as it means you are using public variables. My suggestion is to always make them protected or private unless not possible otherwise (SOAP?). You can access them by getters and setters.

Upvotes: 0

Yogesh Suthar
Yogesh Suthar

Reputation: 30488

$obj is not array its stdClass Object and

because of that $obj->property[0] will show you Undefined offset: 0

try to use it like this for getting 1st value of property

$obj->property->property;

Upvotes: 0

Related Questions