Open In App

How to Get All Values from an Associative Array in PHP?

Last Updated : 24 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Given an Associative Array, the task is to get all values from the associative array in PHP. To get all the values from an associative array, you can use various approaches such as foreach loop, array_values() function, and array_map() function. In this article, we will explore each approach with detailed explanations and code examples.

Approach 1: Get All Values from an Associative Array using foreach Loop

The basic approach is to use a foreach loop to iterate over the associative array and access each value.

PHP
<?php

$student = array(
    "Maths" => 95, 
    "Physics" => 90,   
    "Chemistry" => 96, 
    "English" => 93,   
    "Computer" => 98
);

foreach ($student as $marks) {
    echo "$marks\n";
}

?>

Output
95
90
96
93
98

Approach 2: Get All Values from an Associative Array using array_values() Function

The array_values() function returns all the values of an array in a new array and then use foreach loop to access all values of the new array.

PHP
<?php

$student = array(
    "Maths" => 95, 
    "Physics" => 90,   
    "Chemistry" => 96, 
    "English" => 93,   
    "Computer" => 98
);

$values = array_values($student);

foreach ($values as $value) {
    echo "$value\n";
}

?>

Output
95
90
96
93
98

Approach 3: Get All Values from an Associative Array using array_map() Function

The array_map() function applies a callback function to each value of an array and returns an array with the modified values. After getting the new modified array containing values, we use foreach loop to access all values of the array.

PHP
<?php

$student = array(
    "Maths" => 95, 
    "Physics" => 90,   
    "Chemistry" => 96, 
    "English" => 93,   
    "Computer" => 98
);

$values = array_map(function($value) {
    return $value;
}, $student);

foreach ($values as $value) {
    echo "$value\n";
}

?>

Output
95
90
96
93
98

Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads