The foreach
construct only works with arrays.
This means you must either use an array like this: array( '1', '2', '3' );
Or functions which return an array like get_categories
.
foreach
is used to loop through each key/value pair in an array:
$key = array( '1', '2', '3' );
foreach( $key as $value )
print $value;
If you wrap the above code in opening and closing php tags and put it into a file, it will output 123.
That’s the most basic example of using foreach with an array.
Here’s several commonly used examples of using foreach with an array of key/value pairs as well as functions which return an array.
Add the following functions to your child themes functions file to see what each code snippet outputs on the front end.
Example 1 : Using array with foreach loop
The following example prints the value for each key in the array:
add_action( 'loop_start', 'for_each_example_1' );
function for_each_example_1() {
$key = array( 'Number 1', 'Number 2', 'Number 3' );
foreach( $key as $value )
echo $value;
}
Example 2 : Using array within foreach
A different way to code ( array )
when using foreach
:
add_action( 'genesis_entry_header', 'for_each_example_2' );
function for_each_example_2() {
$key = ( 'note 1, note 2, note 3' );
foreach( ( array ) $key as $value )
echo $value;
}
Example 3 : Using foreach with functions.
This example uses the get_categories
function which returns an array of categories.
add_action( 'genesis_entry_footer', 'for_each_example_3' );
function for_each_example_3() {
$key = get_categories();
foreach( $key as $value )
echo $value->name;
}
Example 4 : Commonly used names for variables using foreach
Generally, you’ll find the name of variables used with foreach won’t be named $key
and $value
but more descriptive like $categories as $category
or $tags as $tag
as seen in the following example:
add_action( 'genesis_after_entry', 'for_each_example_4' );
function for_each_example_4() {
$categories = get_categories();
foreach( $categories as $category )
echo $category->name;
}
Examples of using foreach with get_tags, get_categories and get_terms
Was This Tutorial Helpful?