user1469270
user1469270

Reputation:

Understanding a foreach loop in PHP

I've got two foreach loops, and I'm using an object generated by WordPress.

In my mind, these should both work the same. However, they don't. Notice $post and $not_a_post in the loop:

A:

$array_A = array( 'posts_per_page' => 2 );
$get_posts_A = get_posts( $array_A );

foreach ( $get_posts_A as $post ) { //uses $post
    the_title(); 
}

B:

$array_B = array( 'posts_per_page' => 5 );
$get_posts_B = get_posts( $array_B );

foreach ( $get_posts_B as $not_a_post ) {  //uses $not_a_post
    the_title(); 
 }

The only difference is that I use a variable $post for conditional first loop.

I always thought (apparently, incorrectly) the second conditional variable was just a placeholder. So I could do $x, $y, etc.

Can someone explain to me why this foreach loop requires the variable $post ?

Upvotes: 1

Views: 130

Answers (1)

moonwave99
moonwave99

Reputation: 22817

That's because the_title() relies on a variable named exactly $post coming from the outer scope, which is a terrible design idea by the way - it should be passed as a parameter to the function, e.g.:

the_title($some_id || $some_resource);

EDIT: actually WP allows you to pass the post id, check the code here.

Upvotes: 6

Related Questions