array_keys() | How To Get Key Name of an Associative Array by Indexing Number in PHP

Date Published: 25/03/2020 Published By: JaiSchool

The function array_keys() is a predefined function of PHP. This array_keys() gives us the functionality of accessing the keys of an associative array by indexing numbers.

Table of Contents
Print, key name of an associative array
Print all key names by loop
Print all keys by indexing number of an assoc. array
Print all keys and their values by indexing number, using a loop

To make the associative array keys, accessible by indexing number, pass that associative array in the argument (parameter) of the array_keys() method.

$array = array_keys($assoc_array);

The function keeps associative array's keys by indexing numbers. So that we can get a particular key name at an indexing number by just passing the indexing number.

$array = array_keys($assoc_array);
echo $array[0];

Once we get the key name by indexing number, It is easiest to get/print value of it.

<?php

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

$array = array_keys($assoc_array);

echo $array[0];

?>

To print all the key's names from an associative at once array you need to run a loop that will last till the length of the array. Use sizeof() function to get the length of the array.

<?php

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

$array = array_keys($assoc_array);

$length = sizeof($assoc_array);

for($i=0;$i<$length;$i++)
	{
		echo $array[$i]."<br>";
	}
?>
<?php

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

$array = array_keys($assoc_array);

echo $array[0]." = ".$assoc_array[$array[0]];

?>
<?php

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

$array = array_keys($assoc_array);

$length = sizeof($assoc_array);

for($i=0;$i<$length;$i++)
	{
		$index_num = $array[$i];
		echo $array[$i]." - ".$assoc_array[$index_num]."<br>";
	}
?>
Also, Get These
# Associative array to JSON data
# JSON data to PHP object
# Get a random number in PHP
# array length
# Print an array in PHP
# Getting started with SQL

Publish A Comment

Leave a Reply

Your email address will not be published. Required fields are marked *