Jump to content

Unexpected value when using new each() api method


gebeer
 Share

Recommended Posts

Hello,

I'm playing with the new each() API method.

	$warning = $divesites->each(function($item) {
	  $warning = "";
	  if (!$item->marker->address) {
	  	$warning .= "<div class='alert alert-warning'>coordinates for {title} not set</div>";
	  } else {
	  	$warning .= "";
	  }
	  return $warning;
	});

$warning should return an empty string, when all dive site adresses are set. But instead it returns the page id of the last dive site in the loop.

When I do it the foreach way

        $warning = "";
	foreach ($divesites as $site) {
		if (!$site->marker->address) {
		  	$warning .= "<div class='alert alert-warning'>coordinates for {$site->title} not set</div>";
		  } else {
		  	$warning .= "";
		  }
	}

the $warning is an empty string as expected.

Why is that? Any pointers would be much appreciated.

Link to comment
Share on other sites

Thanks for your reply.

$warning will not be available inside the each() callback function because of variable scope.

Also the callback function needs to either echo or return something.

So I'm afraid your code won't output anything and give a PHP notice like "variable $warning not defined" because you define $warning outside the callback function. This is mentioned in the link that I posted in #1

EDIT

Sorry, I overlooked the "use (&$warning)" part. So forget about what I just said

I implemented your proposed solution. But still the return value gives me the page ids of pages within the $divesites page array where I would expect it to be empty.

EDIT again

Got it. I still had $warning = $divesites->each(function...

After removing the $warning = part, it works.

Only I had to replace {title} with {$item->title}

Thanks again.

But with my limited PHP knowledge I still don't understand why that is so.

  • Like 1
Link to comment
Share on other sites

Glad it worked. :-)

It wouldn't have worked because of variable scope and attempting to assign multiple results to a single variable in one shot. In other words, the $warning = "" would have been reset each time the function executed. That's why the write access (reference) to $warning (outside the function) is needed.

I'm surprised about the {title}, though... Not sure why that had to be changed.

I think the {title} had to be changed because that seems to only be worked with after the function has returned a value. It can't just guess.

  • Like 1
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...