0

I made this object array

$trailheads[] = new StdClass;

Then I was putting an object in there each time it looped

$trailheads[] = $trailhead;

Then I returned the whole thing from the function like this:

$ret->ok = empty($errors);
$ret->errors = $errors;
$ret->o = $trailheads;

return $ret;

Once I got the values back, and loop through the results in the trailheads[] I keep looping 3 times instead of the expected 2. Is there a reason an extra iteration might be happening?

Here is how I try to loop:

foreach ($trailhead_list->o as $key)
{
    $objkey  = (object) $key;
    echo '<p><h3>Trailhead Name: '.$objkey->trailhead_name.'</h3></p>';
    }
1
  • I think you also need to show how you create the trailheads[] entries from what data; and what output you are getting. Commented Jun 3, 2011 at 21:23

3 Answers 3

2

After this:

$trailheads[] = new StdClass;

your $trailheads array contains on element, an instance of StdClass.

Then you add more elements, but there will be that first one.

Maybe you wanted to initialize the $trailheads[] like that, but instead you gave value to one of the array elements. Use this instead:

$trailheads = array();
Sign up to request clarification or add additional context in comments.

Comments

1

This:

I made this object array

$trailheads[] = new StdClass;

... appears to be the source of the extra array element. Instantiate an array empty like this:

$trailheads = array();

Then loop and add objects:

$trailheads[] = $trailhead;

Also a note: I am guessing you don't have notices or warnings enabled. Turn them on while you develop. The line $trailheads[] = new StdClass; would have generated a notice, since you are adding a new element to a variable that hasn't been declared as an array (or anything else). PHP's loose typing is very forgiving, but this line would have generated a notice.

Warnings and notices on while you develop, turn them off for production. It will help you avoid common bugs and it will make you a better programmer to boot.

Comments

0

In the line:

$trailheads[] = new StdClass;

You are assigning a new StdClass object into the $trailheads array. That is to say you aren't declaring it as a variable but actually adding an element.

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.