foreach() Loop for Ordinary Array and Associative Array in PHP

The foreach() is a looping method of PHP. It is an advanced loop. We don’t need to count the length of the array because it automatically calculates the length of an array whether it is an ordinary array or associative array.

Table of Contents
foreach() loop for ordinary array
foreach() loop for associative array
How foreach() loop works

There are some differences when we use foreach() loop with an associative array or normal array in PHP. That we are going to clear.

foreach() loop for an ordinary array in PHP

in the first parameter of foreach() loop, give the ordinary array name to be counted its length and after it, use “as” and next to it get all array data in an arbitrary variable.

To print all data echo this variable. See example

Example~*~

<?php
$ordin_array = ["website","Jaischool","hosting","Siteground","plan","GoGeek",404];

foreach($ordin_array as $all_array_data)
{
	echo $all_array_data."<br>";
}
?>

foreach() loop for an associative array in PHP

In respect of an associative, the thing you will do is just pass the variable name in the foreach() loop’s parenthesis.

After it, use a keyword ‘as‘ just after variable name by giving space.

Now, foreach() loop needs two variables to store key names in it and its values from the associative array. Therefore, create those two and separate them by an object operator (=>).

The syntax for an associative array

foreach($variable as $key => $value) {
	//your code goes here
}

You can use any variable name instead of $key and $value to receive keys names and their values.

Variables in the foreach() argument to receive keys names & its values are separated through an object operator ( => )

Example~*~

<?php

$assoc_array = array("website"=>"Jaischool.com","hosting"=>"Siteground","plan"=>"GoGeek");

foreach($assoc_array as $all_keys => $all_values)
{
	echo $all_keys." - ".$all_values."<br>";
}

?>

How foreach() loop works?

  1. First of all, you pass the array name in the first parameter. Foreach() loop will count its length to execute the statements in it.
  2. And then, it will separately place all the keys names in the variable, we have created just after as keyword in its argument. See the example above.
  3. After that, all the values of keys are placed in a variable after the variable for keys and object operator.

Extra Reading

# get associative array key by numeric index
# Get value of attribute in Jquery
# Introduction to structured query language
# convert array to a string
# Disable forms default behavior of submitting
# Delete a column in sql
# delete data from a table in sql
# add column in a table in sql
# data sorting in sql

Leave a Comment