PHP foreach Loop

PHP foreach Loop with Example PHP foreach loop is used to loop through the associative arrays. Syntax:
foreach($array as $key => $value)
{
//Statement
}
  • $array = associative array.
  • $key = array key.
  • &value = array key`s value.
$key and $value variables can be named anything. The $key will be equal to the array`s key, and $value will be equal to that key`s value. The loop ends when the last array key (=>) value pair reached. Associative Array Example:
$arrayname = array(‘key’ =>value, ‘key’ =>value);
Associative array have named keys. The key names are placed inside single or double quotes and the (=>) is used to assign key value pairs.
<?php
 $students = array('Henry' => 21, 'George' => 19, 'Jonny' => 15);
foreach ($students as $name => $age) {
echo $name.' '.$age.'<br/>';
 }
Output:
Henry 21
George 19
Jonny 15

  • In the above program, we are using an associative array here $students with three keys/values, and we are printing the value of each array element through a foreach loop and an echo function for printing results.
Example2:
<?php
$fruits= array("Mango","Orange","Strawberry");
foreach($fruits as $t)
{
echo $t."<br>";
}
?>
Output:
Mango
Orange
Strawberry
  • In the above program, an array of$fruits contains three elements. For each loop iteration, here the value of current array element is assigning to the variable $t, an array pointer is moving by one and displaying the value of each array element until the last array element found.
Example3:
<?php
function sub()
 {
$s=array("PHP","JAVA","C","R");
foreach ($s as $a)
 {
echo $a."<br>";
}
 }         
sub();
?>
Output:
PHP
JAVA
C
R
  • In the above program, we are using a user-defined function sub, and the function body is containing an array $s with four elements, and we are displaying the value of each array element using a foreach loop.
Example4:
<?php
function fruit($f)
{
foreach($f as $s)
{
echo $s."<br>";
}
}
$f1=array("Apple","Cherry");
fruit($f1); //calling function by passing array
?>

Output:
Apple
Cherry
  • In the above, program is containing a user-defined function fruit, and an array is passing as an argument to the function. The function is containing a foreach loop, through this loop we are displaying the value of each array element with an echo statement. When a function is called, then the function body will be executed.

Related Topics

PHP Variables

PHP Variable is the name of memory location used to hold the data.  In PHP, variable starts with $ symbol. Rules for PHP Variables. Variable starts with $ sign. Variable name...

2 minutes read.

PHP For Loops

PHP for loop is used when the specified condition is predefined. Syntax: for (initialization; condition; increment/decrement ) { code to be executed; } Example <!DOCTYPE html> <html> <head> <title>PHP Tutorial</title> </head> <body> <?php echo " Print counting using for loop"."<br>"; for($i=1;$i<=5;$i++){ echo $i."<br>"; } ?> </body> </html> Output Print counting using...

1 minute read.

PHP array_shift() Function

PHP array_shift() Function The array_shift() in PHP shifts the first value of the array off. This function returns the same value after shortening the array by one element and moving everything. Syntax array_shift ( array &$array )  Parameter array(required)- This parameter represents the input array Return This function returns...

1 minute read.

PHP array_intersect_ukey() function

The array_intersect_ukey () function in PHP is used to compute the intersection of arrays with the help of a callable function on the keys for comparison. It returns an array containing all the...

1 minute read.

PHP key_exists() Function

PHP key_exists() Function The key_exists() function in PHP checks if the specified key or index exists in the array or not. Syntax key_exists ( mixed $key , array $array )  Parameter key(required)- This parameter represents the value to check. array(required)- This parameter signifies an input array with...

1 minute read.

PHP key() Function

PHP key() Function The key() function in PHP fetches a key from an array and returns the index element of the current array position. Syntax key ( array $array ) Parameter array(required)- This parameter represents the input array. Return This function returns the key of the...

1 minute read.

PHP Indexed Array

In PHP, arrays are linear data structures that allow to store multiple elements of the same type under a single variable which helps in saving the time and effort of...

3 minutes read.

PHP levenshtein() Function

PHP levenshtein() Function The levenshtein() function in PHP calculates the Levenshtein distance between two strings. Syntax levenshtein ( string $str1 , string $str2 , int $cost_ins , int $cost_rep , int $cost_del )  Parameter str1(required)- This parameter signifies one of the strings being evaluated for Levenshtein distance. str2(required)- This parameter signifies one of the strings being evaluated...

1 minute read.

PHP sha1() Function

PHP sha1() Function The sha1() in PHP calculates the SHA-1 hash of a string. Syntax sha1 ( string $str [, bool $raw_output = FALSE ] )  Parameter str (required)- This parameter represents the input string. raw_output(optional)- This parameter takes Boolean value and returns the digest in raw binary format...

1 minute read.

PHP print() Function

PHP print() Function The print() function in PHP is used to output one or more string. Syntax print ( string $arg ) Parameter arg(required)- This parameter represents the input data. It can take one or more arguments. Return This function returns an integer value 1. Example...

1 minute read.

PHP Include Function

PHP Include( ) The PHP include() statement holds all the code/text that liesin the defined file and paste it into the file that uses the "include" statement. With the help of include...

3 minutes read.

How to use Date and Time in PHP

HOW TO USE DATE AND TIME IN PHP: PHP time and date function  informs us about current date and time. it can be manipulated also. How time() function works: The time() function...

2 minutes read.

PHP krsort() Function

PHP krsort() Function The krsort() function in PHP sorts an array by key in reverse order while maintaining the keys. Syntax krsort (array & $array[,int $sort_flags= SORT_REGULAR] ) Parameter array(required)- This parameter represents the input array. sort_flags(optional)- This...

3 minutes read.

PHP rsort() Function

PHP rsort() Function The rsort () function in PHP is used to sort an array in reverse order i.e., highest to lowest. Syntax rsort ( array &$array [, int $sort_flags = SORT_REGULAR ] ) Parameter array(required)- This parameter represents the input array. sort_flags (optional)- This parameter is used to...

1 minute read.

PHP str_replace() Function

PHP str_replace() Function The str_replace() function in PHP replaces all occurrences of the search string with the specified replacement string. This function is case-sensitive. Syntax str_replace ( mixed $search , mixed $replace , mixed $subject [, int &$count ] ) Parameter search(required)- This parameter signifies the value to search. replace(required)-...

1 minute read.

PHP quoted_printable_decode() Function

PHP quoted_printable_decode() Function The quote_printable_decode() function of PHP converts a quoted-printable string to an 8 bit string. It works similar to imap_qprint(), except this one does not require the IMAP module to work. Syntax quoted_printable_decode ( string $str ) Parameter str(required)- This parameter represents the...

1 minute read.

PHP strrchr() Function

PHP strrchr() Function The strrchr() function in PHP finds the last occurrence of a character in the specified string and returns the portion of haystack, which starts at the last occurrence of the needle and goes until the end of haystack....

1 minute read.

PHP natcasesort() Function

PHP natcasesort() Function The natcasesort() function in PHP Sort an array using a case insensitive "natural order" algorithm while maintaining the keys. Syntax natcasesort ( array &$array ) Parameter array(required)- This parameter represents the input array. Return This parameter returns a Boolean...

1 minute read.

PHP pos() Function

PHP pos() Function The pos() function in PHP returns the current element in an array which is initialized to the first element of the array. This function is an alias of current(). Syntax pos ( array...

1 minute read.

PHP stripcslashes() Function

PHP stripcslashes() Function The stripcslashes() function in PHP returns a string with backslashes(\n, \r ..., octal and hexadecimal representation) stripped off. Syntax stripcslashes ( string $str )  Parameter str(required)- This parameter signifies the string to be unescaped. Return This function returns the unescaped string with backslashes stripped off. Example 1   ...

1 minute read.