How to get the Index in foreach loop php?

In this tutorial, we are going to check how to get Index value in foreach loop PHP.


In the foreach construct, the variable is a data type called an iterator. The exact definition of this depends on what implementation of foreach you’re using, but basically, it represents a sequence of values from a collection.

In a PHP array, for example, each element in the array can be thought of as being stored in an iterator that allows you to go through all of the elements in the array one by one. You can also use break to break out of the current loop.

When using foreach, $value represents each element of the iterable in turn, with $key representing a control variable that’s set to hold the key associated with each value as it’s iterating over.

You’ll see in this example that how we are able to get indexed value in foreach loop PHP.

Example 1:

<?php 
	$fruits = [ 'apple', 'banana', 'mango'];

	foreach($fruits as $key => $value) {         
		
		echo "key = $key | value = $value <br/>";
	} 
?>

Output:

key = 0 | value = apple
key = 1 | value = banana
key = 2 | value = mango

Example 2:

<?php 
	$topics = array(
		"a" => "get ",
		"b" => "Index",
		"c" => "in",
		"d" => "foreach",
		"d" => "loop"
	);

	foreach($topics as $key => $value) {         
		
		echo "key = $key | value = $value <br/>";
	} 
?>

Output:

key = a | value = get
key = b | value = Index
key = c | value = in
key = d | value = loop

Example 3:

<?php 
	 
	//multi-dimensional array
	$multi_array = array(
		array('a', 'b', 'c'), 
		array('d', 'e', 'f'),
		array('g', 'h', 'i')
	);
	  
	// Iterate through the array using foreach
	//and display all key and value
	foreach ($multi_array as $outer_array_key => $outer_array_value) {
		
		foreach($outer_array_value as $inner_array_key => $inner_array_value) {
			echo "key = ( $outer_array_key  $inner_array_key ), value = $inner_array_value<br/>";    
		}
	}
?>

Output:

key = ( 0 0 ), value = a
key = ( 0 1 ), value = b
key = ( 0 2 ), value = c
key = ( 1 0 ), value = d
key = ( 1 1 ), value = e
key = ( 1 2 ), value = f
key = ( 2 0 ), value = g
key = ( 2 1 ), value = h
key = ( 2 2 ), value = i

Conclusion

In this post, we have given you a few tips on how to get an index in foreach loop php. We hope that it will help you solve your problem and achieve what you want from the code. If not, please let us know so that we can continue assisting with any other issues or questions!

About Ashis Biswas

A web developer who has a love for creativity and enjoys experimenting with the various techniques in both web designing and web development. If you would like to be kept up to date with his post, you can follow him.

Leave a Comment