Laravel

PHP Beginner’s Guide: How to Get and Compare the Next Element Using foreach

Hello! In this article, we will clearly explain how to manipulate arrays using the foreach statement in PHP. PHP is a widely used language for web development. By reading this article, you’ll learn basic PHP operations and further improve your programming skills.

We’ll show you how to get the next element (the following one) from the current one in a foreach loop and compare them.

What is foreach?

First, let’s briefly explain the foreach statement. The foreach statement is a syntax used to iterate over arrays or objects. By using it, you can perform operations on each element of an array individually.

Preparing array data

Now, let’s create an array in PHP. The following code is an example of an array containing name, gender, age, and email address.

$valus = [
    0 => [
        "name" => "Taro",
        "sex" => "man",
        "age" => 30,
        "email" => "a0@dad-union.com"
    ],
    1 => [
        "name" => "Ichiro",
        "sex" => "man",
        "age" => 31,
        "email" => "b1@dad-union.com"
    ],
    2 => [
        "name" => "Jiko",
        "sex" => "woman",
        "age" => 22,
        "email" => "c2@dad-union.com"
    ]
];

PHP code to compare current and next elements using foreach

Next, let’s see how to compare each element in the array using a foreach loop. The goal here is to compare the ages of people in the array and determine who is older.
We compare the current element with the next one in foreach and output a message based on the comparison.

<?php
foreach ($valus as $key => $valu) {
	if ($valus[$key]['age'] > $valus[$key + 1]['age']) {
		echo $valus[$key]['name']." is older than ".$valus[$key + 1]['name'].".";
	}
}
?>

Usage in Laravel Blade files

In addition to basic PHP usage, we’ll also introduce how to use it in Blade templates, which are part of the Laravel PHP framework. Blade is designed to make writing PHP easier and more convenient.
When using foreach in a Laravel Blade file, you can write it as shown below. You can directly use the content from the section “PHP code to compare current and next elements using foreach” in a Blade file without issue.

@foreach ($valus as $key => $valu) {
<?php
	if($valus[$key]->age > $valus[$key + 1]->age){
		echo $valus[$key]->name." is older than ".$valus[$key + 1]->name.".";
	}
?>
@endforeach

Conclusion

That’s it for learning the basics of array manipulation using the foreach statement in PHP. These fundamental techniques are very important in PHP programming. Use this knowledge to add more versatile functionality to your programs.

 
*Please use at your own risk if reusing this content.