Understanding PHP's array_values Function with Examples

The array_values function in PHP is used to extract all values from an array, regardless of their original keys. It returns a new array with the extracted values, indexed numerically starting from 0. This function is helpful when you need to work with the values of an array without considering their original keys.

Important Points:
  • array_values does not affect the original array. It only creates and returns a new array with the extracted values.
  • If the original array contains duplicate values, the new array will also contain duplicate values.
  • The new array will be indexed numerically, starting from 0.

 
$schools = array(
  "school_1" => array("name" => "St. John's School"),
  "school_2" => array("name" => "Central High School"),
  "school_3" => array("name" => "Green Valley Academy"),
);
 
// Get an array containing only the school names
$schoolNames = array_values($schools);
 
// Print the school names
print_r($schoolNames);
 
This code will print the following output:
 

Array
(
    [0] => Array
        (
            [name] => St. John's School
        )
    [1] => Array
        (
            [name] => Central High School
        )
    [2] => Array
        (
            [name] => Green Valley Academy
        )
)
 
 

 
 
$schools = [
  [
    "id" => 1,
    "name" => "St. John's School",
  ],
  [
    "id" => 2,
    "name" => "Green Valley School",
  ],
  [
    "id" => 3,
    "name" => "Sunrise Academy",
  ],
];
 
$schoolNames = array_values(array_column($schools, "name"));
 
print_r($schoolNames);
 
 
This code snippet first extracts the "name" values from each sub-array using array_column. Then, it uses array_values to extract those values and create a new array with numerical indexes. This will print the following output:
 

Array
(
    [0] => St. John's School
    [1] => Green Valley School
    [2] => Sunrise Academy
)