CodeBlanks Logo Icon CodeBlanks

array_keys() and array_values()

PHP course · Beginner · Lesson 67/116

Learn to get all keys with array_keys() and all values with array_values().

array_keys() and array_values()

Sometimes you want only the keys or only the values of an associative array. array_keys() returns the keys as a new numeric array; array_values() returns the values the same way.

For example with $user = ["name" => "Alex", "age" => 28], array_keys($user) returns ["name", "age"]; array_values($user) returns ["Alex", 28]. The original keys are gone and a zero-based index is given.

Renumbering an indexed array

When you remove an item from a numeric array with unset() the indexes keep gaps; for example [0 => "a", 2 => "c"]. array_values() takes that array and renumbers the indexes starting from 0.

That lets you walk it again with a for loop in order. The same function can reset the key-value mapping on an associative array.

Exercise Print the cart keys

Create the $cart associative array with "apple" => 3, "bread" => 2, "milk" => 1. Then get the keys with array_keys($cart) and print them with print_r.

Show example solution
Define the array; then write print_r(array_keys($cart));
Example solution:
<?php
// Print the cart keys
$cart = ["apple" => 3, "bread" => 2, "milk" => 1];
print_r(array_keys($cart));

Test yourself

  1. What does array_keys($user) return?

    $user = ["name" => "Alex", "age" => 28];
    • ["Alex", 28]
    • ["name", "age"]
    • ["name" => "Alex", "age" => 28]
    • [0, 1]
    Show answer

    ["name", "age"] — Correct. array_keys() returns only the keys as a numeric array.

  2. Get the values

    $prices = ["apple" => 5, "banana" => 7];
    $only_values = ____($prices);
    Show answer
    $prices = ["apple" => 5, "banana" => 7];
    $only_values = array_values($prices);
  3. What is the difference between array_keys and array_values?

    • array_keys returns keys, array_values returns values
    • array_keys returns values, array_values returns keys
    • Both do the same thing
    • array_keys returns only numeric keys
    Show answer

    array_keys returns keys, array_values returns values — Correct. array_keys() returns the keys and array_values() returns the values.

All lessons in Beginner