Signup/Sign In
LAST UPDATED: AUGUST 4, 2021

How to get single value from an array in PHP?

Answer: Using array index or key

In this lesson, we will learn how to get the single value from the array in PHP.

There are three types of the array in PHP, which are:

  • index array
  • associative array
  • multi-dimensional array

We can get a single value from any of the arrays using the array index or key.

Getting value from an indexed array

In an indexed array, all the array elements are represented by the index, which is a numeric value starting from 0 (zero). We can get the single array value from the indexed array either using array index or key.

Example: Getting a single value from an indexed array

In this example, we have accessed the single value from the indexed array using the array index.

<!DOCTYPE html>
<html>
<head>
  <title>Getting single value from an array</title>
</head>
<body>
	<?php 
		$proglang = array("C", "C++", "JavaScript", "jQuery", "PHP");
		echo $proglang[0]; 
		echo "<br>";
		echo $proglang[2]; 
		echo "<br>";
	?>
</body>
</html>

Output


C
JavaScript

Getting value from an associative array

In an associative array, elements are stored in the form of key-value pairs. The index of the associative array is in the form of a string so that we can establish a strong association between key and values. We can get the single value from an associative array using the key.

Example: Getting value from an associative array

In this example, we have accessed the single value from the associative array using the key.

<!DOCTYPE html>
<html>
<head>
  <title>Getting single value from an array</title>
</head>
<body>
	<?php 
		$empId = array("Harry"=>1234, "John"=> 1235, "Miley"=>1236, "Williams"=>1237);
		echo $empId["Harry"]; 
		echo "<br>";
		echo $empId["Miley"];
		echo "<br>";
	?>
</body>
</html>

Output


1234
1236

Getting value from the multidimensional array

The multi-dimensional arrays are those arrays that contain one or more than one array as its value. We can get the single value from the multi-dimensional array using the index value and the array key as well.

Example: Getting value from the multidimensional array

In this example, we have accessed the single value from the array using both array index and key.

<!DOCTYPE html>
<html>
<head>
  <title>Getting single value from an array</title>
</head>
<body>
	<?php 
		$employee = array(
		array(
		"name" => "Harry",
		"empid" => "110",
		),
		array(
		"name" => "John",
		"age" => "111",
		));
		echo $employee[0]["name"]; 
	?>
</body>
</html>

Output


Harry

Conclusion

In this lesson, we have learned how to get the single value from the array in PHP. We learned to fetch either by using the array index or key value.



About the author:
I am the founder of Studytonight. I like writing content about C/C++, DBMS, Java, Docker, general How-tos, Linux, PHP, Java, Go lang, Cloud, and Web development. I have 10 years of diverse experience in software development.