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





Was this page helpful? Please share with your friends...

Are you a blogger? Join our Blogging forum.



Comments and Discussions





© https://www.includehelp.com (2015-2018), Some rights reserved.




close Like other websites, this site uses cookies to deliver relevant ads based on your interest, by using our website, you acknowledge that you have read our privacy policy.