I have a foreach like so:
foreach ($posts as $post) {
$postArray[] = array(
"title" => $post->title,
"date" => date("d.m.Y", $post->created),
// ... etc
);
var_dump($postArray);
}
$postArray is not delcared anywhere outside of this loop, and yet each loop iteration is ADDING to the existing array as if this variable is global, rather than creating a new one!
Is this a PHP setting? Bearing in mind I haven’t really changed any settings from whatever default WAMP gives me. Any ideas?
It is not a global variable but the way your syntax is written, it becomes global after the first iteration. This is because you are using the
array_pushshorthand of[]. Usually we use this as a synonym toarray_push()What you want to do is this –
That way, on each iteration, you will get a brand new
$postArrayobject.