Home » PHP

How to get the index of the current array element position using key() function in PHP?

PHP key() function Example: Here, we are going to learn how to get the index of an element in an array which is currently pointing by the internal pointer?
Submitted by IncludeHelp, on March 08, 2018

To get the current pointing element’s index, we use key() function.

key() function is a library (predefined) function in PHP, which is used to return the index of current element in an array which is pointing.

Note: By default, index of current position is 0 (Zero).

In this program, we are declaring an array with some of the strings and printing the index using key() function. Here, we are also using next() function – that will move the pointer to next array element.

Example:

<?php
	//array elements
	$arr = array("C", "C++", "Java", "PHP");
	 
	//printing the index of current element
	echo "Index is: ". key($arr) . "<br>";

	//moving to the next element
	next($arr);
	//now print the index
	echo "Index is: ". key($arr) . "<br>";

	//moving to the next element
	next($arr);
	//now print the index
	echo "Index is: ". key($arr) . "<br>";
?>

Output

Index is: 0
Index is: 1
Index is: 2


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.