Arrays with keys

PHP arrays are actually ordered maps, meaning that all values of arrays have keys, and the items inside the array preserve order. When using arrays as simple lists as we have seen last chapter, a zero based counter is used to set the keys. Each item which is added to the array increments the next index by 1.

A good example for using arrays with keys is a phone book. Let's say we want to save the phone numbers of people in a class.

To add an item to an array using a key, we use the brackets operator, as you would expect.

To check if a key exists within an array, we can use the array_key_exists function:

If we want to extract only the keys of the array (the names), we can use the array_keys function.

Alternatively, to get only the values of an array (the phone numbers), we can use the array_values function.

Add a number to the phone book for Eric, with the number 415-874-7659, either by adding it to the array definition, or as a separate code line.

Sphere Engine

Home » PHP Tutorial » PHP array_keys

PHP array_keys

Summary : in this tutorial, you will learn how to use the PHP array_keys() function to get the keys of an array.

Introduction to the PHP array_keys function

The PHP array_keys() function accepts an array and returns all the keys or a subset of the keys of the array.

In this syntax:

  • $array is the input array.
  • $search_value specifies the value of the keys to search for.
  • $strict if it sets to true , the array_keys() function uses the identical operator (===) for matching the search_value with the array keys. Otherwise, the function uses the equal opeartor (==) for matching.

The array_keys() function returns an array that contains all the keys in the input array.

PHP array_keys() function examples

Let’s take some examples of using the array_keys() function.

1) Using the array_keys() function example

The following example shows how to get all keys of an indexed array:

How it works.

  • First, define an array that contains three numbers.
  • Second, use the array_keys() function to get all the keys of the $numbers array.
  • Third, display the keys.

Since the $numbers is an indexed array, the array_keys() function returns the numeric keys of the array.

The following example uses the array_keys() function to get the keys of the array whole value is 20:

The array_keys() function returns the key 1 because key 1 contains the value 20.

2) Using PHP array_keys() function with an associative array example

The following example illustrates how to use the array_keys() function with an associative array:

  • First, define an associative array $user that contains three keys username , email , and is_active .
  • Second, get the keys of $user array using the array_keys() function.
  • Third, show the returned keys.

The following example uses the array_keys() function to get the keys whose values equal 1:

The array_keys() function returns one key, which is is_active . However, the is_active contains the string '1' , not the number 1 . This is because the array_keys() uses the equality (==) operator for comparison in searching by default.

To enable the strict equality comparison (===) when searching, you pass true as the third argument of the array_keys() function like this:

Now, the array_keys() function returns an empty array.

Finding array keys that pass a test

The following function returns the keys of an array, which pass a test specified a callback:

The following example uses the array_keys_by() function above to find the keys that contain the string '_post' :

  • Use the PHP array_keys() function to get all the keys or a subset of keys in an array.

Education, Online Course, LMS Creative

  • Login Login

PHP Articles

  • PHP Get Keys Of Array

Line Shape Image

Php Get Keys Of Array

  • Amara Singh
  • Nov 07, 2023

Switch to English

  • Introduction

Table of Contents

Understanding PHP Arrays

  • PHP Get Keys of Array: The array_keys() Function

Tips and Tricks

Common error-prone cases and how to avoid them.

  • Arrays in PHP are data structures that allow us to store multiple values in a single variable. They can be indexed or associative.
  • Indexed arrays have numeric keys, while associative arrays have string keys.
  • The keys of an array can be used to access the corresponding values.

PHP Get Keys of Array: The array_keys() Function Upskill yourself, get started with AI courses 🚀

  • The array_keys() function in PHP is used to fetch all the keys in an array.
  • It returns an array containing the keys.
  • The syntax is as follows: array_keys(array, value, strict)
  • The function accepts three parameters - array (required), value (optional), and strict (optional).
  • The array_keys() function can also be used to fetch keys for a specific value. For instance, if we want to get the keys associated with the value 21 in the $student array, we would write array_keys($student, 21).
  • If the strict parameter is set to true, the array_keys() function will check the data type of the value in the array. By default, it is set to false.
  • Trying to get keys from a variable that is not an array will result in an error. Always check if the variable is an array before using array_keys(). This can be done using the is_array() function.
  • Passing the wrong data type for the value or strict parameters will also lead to errors. Make sure to pass the correct data types.

Ready to kick-start your career?

Shape Image

PHP array_keys() Function

In this article, we’ll explore PHP array_keys() function and how it can be used in your PHP code. If you’re a PHP programmer, you’ve likely used arrays at some point. Arrays are an essential part of programming in PHP , as they allow you to store and manipulate multiple values in a single variable.

One function that you may find useful when working with arrays is the array_keys() function.

  • What is array_keys() Function?:
  • Parameter Values:
  • Using the array_keys() function:
  • Case-sensitive Searches:
  • Searching for a Specific Value:
  • Understanding Undefined Array Keys:

What is array_keys() Function?

PHP array_keys() is a built-in function that returns an array containing the keys of an array. In other words, it returns an array of all the keys in the array that you pass to it. There is only one parameter needed to call this function, and that is the array whose keys need to be retrieved.

It is possible to use this function in situations where you need to obtain all the keys in your array. This is when you want to iterate over an array of associative keys and apply some action to each key in your array; this is the most efficient function to perform.

Parameter Values

Using the array_keys() function.

To use the Func array keys / array_keys() function, you first need to have an array that you want to get the keys from.

A list of keys is returned in the form of an array:

Example: 

Case-sensitive searches.

By default, the Func array keys / array_keys() function performs a case-insensitive search. This means that if you search for a value that is capitalized differently than the values in the array, the function will still find it.

Searching for a Specific Value

If you want to get the keys of only the elements in an array that have a specific value, you can pass that value as the second parameter to the Func array keys OR  array_keys() function.

The value parameter can be used as follows:

Example Explanation:

In this example, we are using PHP to create an array called $array1 , which contains a mix of numbers and a string: 2, 6, 8, 9, “45”, 8, and 4.

We then use the array_keys function to search for the value “ 45 ” within $array1 , and return an array containing the keys (indexes) of any matching elements. The second argument of array_keys, true, indicates that we want an exact match.

Finally, we use the print_r function to output the resulting array of keys.

Understanding Undefined Array Keys

As you work with PHP arrays, you might encounter situations where you try to access an element using a specific key, but that key doesn’t exist. This results in a pesky “ Undefined array key ” warning, potentially causing your code to break. But fret not! With a few smart techniques, you can gracefully handle these scenarios without breaking a sweat.

Example 1: Checking for Key Existence

One of the simplest ways to avoid the “Undefined array key” warning is to check if the key exists before accessing it. We can do this using the isset() function.

In this example, we have an array containing information about celebrities. Before accessing the value of the ‘Brad Pitt’ key, we check if it exists using isset() . If the key is found, we display the celebrity’s profession; otherwise, we inform the user that the information is not available.

Example 2: The Ternary Operator

PHP offers a concise way to handle this scenario using the ternary operator. Let’s see how it works:

Here, we have an array with fruit colors. Instead of writing an if-else block, we utilize the ternary operator to check for key existence. If the key exists, we assign the corresponding color to the $color variable; otherwise, we set it to “ unknown .”

In conclusion, PHP  array_keys() is a useful tool to have in your PHP arsenal when working with arrays. It allows you to quickly get an array of all the keys in an array, or only the keys of elements with a specific value. It also allows you to perform case-insensitive or case-sensitive searches, depending on your needs. With this knowledge , you should be able to use the array_keys() function effectively in your PHP code.

Please subscribe to our newsletter below in order to stay up to date with all the latest developments in PHP Array Function and to learn more about the language.

icon

Feeling bored?

Revitalize and stimulate your mind by solving puzzles in game.

php array assign keys

Mrexamples 1024 Move Game

  • Function Reference
  • Variable and Type Related Extensions
  • Array Functions

array_key_first

(PHP 7 >= 7.3.0, PHP 8)

array_key_first — Gets the first key of an array

Description

Get the first key of the given array without affecting the internal array pointer.

Return Values

Returns the first key of array if the array is not empty; null otherwise.

Example #1 Basic array_key_first() Usage

The above example will output:

There are several ways to provide this functionality for versions prior to PHP 7.3.0. It is possible to use array_keys() , but that may be rather inefficient. It is also possible to use reset() and key() , but that may change the internal array pointer. An efficient solution, which does not change the internal array pointer, written as polyfill:

  • array_key_last() - Gets the last key of an array
  • reset() - Set the internal pointer of an array to its first element

User Contributed Notes 2 notes

To Top

PHP Tutorial

Php advanced, mysql database, php examples, php reference, php array() function.

❮ PHP Array Reference

Create an indexed array named $cars, assign three elements to it, and then print a text containing the array values:

Definition and Usage

The array() function is used to create an array.

In PHP, there are three types of arrays:

  • Indexed arrays - Arrays with numeric index
  • Associative arrays - Arrays with named keys
  • Multidimensional arrays - Arrays containing one or more arrays

Syntax for indexed arrays:

Syntax for associative arrays: 

Parameter Values

Technical details.

Advertisement

More Examples

Create an associative array named $age:

Loop through and print all the values of an indexed array:

Loop through and print all the values of an associative array:

Create a multidimensional array:

Get Certified

COLOR PICKER

colorpicker

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

[email protected]

Top Tutorials

Top references, top examples, get certified.

IMAGES

  1. PHP Array

    php array assign keys

  2. PHP : array_keys() function

    php array assign keys

  3. php

    php array assign keys

  4. PHP array_keys() Function

    php array assign keys

  5. How to get keys of an array in PHP?

    php array assign keys

  6. Creating Array in PHP using Key & values and displaying elements by

    php array assign keys

VIDEO

  1. php://input

  2. Searching array value PHP Tutorial

  3. Styling Dynamic PHP Array Data with CSS

  4. Array In PHP

  5. Office Left Karte Time jab Boss Extra Kaam Assign Kar De Tab Mera Expression #coding #software

  6. How to assign user defined keys on DM7 Yamaha Digital Audio mixer

COMMENTS

  1. How to add keys to php array?

    How to add keys to php array? [duplicate] Ask Question Asked 6 years, 7 months ago 6 years, 7 months ago Viewed 21k times Part of PHP Collective 2 This question already has answers here : How to push both value and key into PHP array [duplicate] (21 answers) Closed 1 year ago.

  2. PHP: array_keys

    strict Determines if strict comparison (===) should be used during the search. Return Values ¶ Returns an array of all the keys in array . Examples ¶ Example #1 array_keys () example <?php $array = array (0 => 100, "color" => "red"); print_r(array_keys($array)); $array = array ("blue", "red", "green", "blue", "blue");

  3. PHP: array_fill_keys

    Array of values that will be used as keys. Illegal values for key will be converted to string . value Value to use for filling Return Values ¶ Returns the filled array Examples ¶ Example #1 array_fill_keys () example <?php $keys = array ('foo', 5, 10, 'bar'); $a = array_fill_keys($keys, 'banana'); print_r($a); ?> The above example will output:

  4. PHP: Arrays

    A map is a type that associates values to keys. This type is optimized for several different uses; it can be treated as an array, list (vector), hash table (an implementation of a map), dictionary, collection, stack, queue, and probably more. As array values can be other array s, trees and multidimensional array s are also possible.

  5. PHP Associative Arrays

    Associative arrays are arrays that use named keys that you assign to them. Example $car = array("brand"=>"Ford", "model"=>"Mustang", "year"=>1964); var_dump($car); Try it Yourself » Access Associative Arrays To access an array item you can refer to the key name. Example Display the model of the car:

  6. Arrays with keys

    PHP arrays are actually ordered maps, meaning that all values of arrays have keys, and the items inside the array preserve order. When using arrays as simple lists as we have seen last chapter, a zero based counter is used to set the keys. Each item which is added to the array increments the next index by 1.

  7. How do I assign names to keys when creating a PHP associative array

    Asked 12 years, 5 months ago Modified 2 years, 7 months ago Viewed 14k times Part of PHP Collective 2 Let's say I have an associative array listing animals at the zoo and some of their features, like so: $zoo => array( "grizzly" => array( "type" => "Bear", "legs" => 4, "teeth" => "sharp", "dangerous" => "yes" ), "flamingo" => array(

  8. PHP array_keys() Function

    Definition and Usage The array_keys () function returns an array containing the keys. Syntax array_keys ( array, value, strict ) Parameter Values Technical Details More Examples Example Using the value parameter: <?php $a=array("Volvo"=>"XC90","BMW"=>"X5","Toyota"=>"Highlander"); print_r (array_keys ($a,"Highlander")); ?> Try it Yourself » Example

  9. Learn PHP: Learn PHP Arrays Cheatsheet

    In a PHP ordered array, the index locations are the keys. However, the PHP array type also allows us to assign meaningful keys to values. These data structures are called associative arrays. For example, in the following associative array table, the key "num_legs" points to the value 4, and the key "material" points to the value "wood":

  10. PHP: array

    Arrays Array Functions Change language: Report a Bug array (PHP 4, PHP 5, PHP 7, PHP 8) array — Create an array Description ¶ array ( mixed ...$values ): array Creates an array. Read the section on the array type for more information on what an array is. Parameters ¶ values

  11. PHP array_keys()

    Summary: in this tutorial, you will learn how to use the PHP array_keys() function to get the keys of an array. Introduction to the PHP array_keys function. The PHP array_keys() function accepts an array and returns all the keys or a subset of the keys of the array.

  12. php

    With the logic of PHP, the best way I can see this being done is to assign your variable variables outside the array definition: $id = 1; $age = 2; $sort = "id"; // or "age"; $Key = $$sort; $arr = array ($Key => 'string'); print_r ($arr); Which outputs: Array ( [1] => string ) Though, personally. I'd suggest avoiding this method.

  13. Understanding and Using PHP Array Keys: A Comprehensive Guide

    The array_keys () function in PHP is used to fetch all the keys in an array. It returns an array containing the keys. The syntax is as follows: array_keys (array, value, strict) The function accepts three parameters - array (required), value (optional), and strict (optional).

  14. PHP Arrays

    Try it Yourself » What is an Array? An array is a special variable that can hold many values under a single name, and you can access the values by referring to an index number or name. PHP Array Types In PHP, there are three types of arrays: Indexed arrays - Arrays with a numeric index Associative arrays - Arrays with named keys

  15. Array_keys() In PHP

    PHP array_keys () is a built-in function that returns an array containing the keys of an array. In other words, it returns an array of all the keys in the array that you pass to it. There is only one parameter needed to call this function, and that is the array whose keys need to be retrieved.

  16. PHP: array_change_key_case

    If an array has indices that will be the same once run through this function (e.g. "keY" and "kEY"), the value that is later in the array will override other indices. + add a note User Contributed Notes 20 notes

  17. PHP: Reassign array keys

    PHP: Reassign array keys Ask Question Asked 12 years, 6 months ago Modified 12 years, 6 months ago Viewed 14k times Part of PHP Collective 6 I have an array of numbers from descending order. When I add to this array, I add to the end and then do natsort ($times). $times then looks like this (obtained by print_r):

  18. PHP: array_key_first

    string (1) "a" Notes ¶ Tip There are several ways to provide this functionality for versions prior to PHP 7.3.0. It is possible to use array_keys (), but that may be rather inefficient. It is also possible to use reset () and key () , but that may change the internal array pointer.

  19. php

    1 You can do it like below:-

  20. PHP array() Function

    Syntax Syntax for indexed arrays: array ( value1, value2, value3, etc.) Syntax for associative arrays: array ( key=>value,key=>value,key=>value,etc.) Parameter Values Technical Details More Examples Example Create an associative array named $age: <?php $age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");

  21. php

    I want to create my data with a new array. But when I assign an array, I want to print out the keys with their id. When I do the operation, ids are not added and array keys start from 0.

  22. mapping

    I have excel sheet with list of types and each types has labels and each labels has values in excel I am trying to collect in array as Key & Value so that I can upload in server enter image description here As per attachment we have multiple types and each type has labels dynamic