DEV Community

ライフポータル
ライフポータル

Posted on • Originally published at code-izumi.com

PHP Associative Arrays: Mastering array_keys, foreach, and Search Functions

In PHP web development, you deal with complex associative arrays almost every day—whether they are database results or API responses.

Commonly, you'll find yourself needing to:

  • "Extract the keys instead of the values."
  • "Identify keys that meet a specific condition."
  • "Look up a key based on a known value."

PHP offers a vast array of built-in functions, and choosing the right one is key to writing clean, efficient code. In this guide, we’ll cover everything from the standard array_keys to modern best practices introduced in PHP 7.3+.


1. Extracting All Keys: array_keys()

If you need a list of every key in an associative array, the standard array_keys() function is your go-to tool. It returns a new indexed array containing only the keys.

Basic Usage

<?php
$userData = [
    'name'   => 'Taro Tanaka',
    'age'    => 28,
    'gender' => 'male',
    'city'   => 'Tokyo'
];

// Get all keys
$keys = array_keys($userData);

print_r($keys);
?>
Enter fullscreen mode Exit fullscreen mode

Output:

Array
(
    [0] => name
    [1] => age
    [2] => gender
    [3] => city
)
Enter fullscreen mode Exit fullscreen mode

This is particularly useful when you need to generate header rows for CSV exports or verify if a set of required parameters is present.

Filtering by Value

A lesser-known feature of array_keys() is its second argument, which allows you to extract only the keys that match a specific value.

$scores = ['UserA' => 80, 'UserB' => 100, 'UserC' => 80];
$targetKeys = array_keys($scores, 80);

// Result: ['UserA', 'UserC']
Enter fullscreen mode Exit fullscreen mode

2. Iterating Through Keys: foreach

In real-world applications, you often need to process both the key and the value simultaneously. The foreach loop is the most common and readable way to achieve this.

The Key-Value Syntax

<?php
$products = [
    'apple'  => 150,
    'orange' => 100,
    'banana' => 200
];

foreach ($products as $name => $price) {
    echo "The price of " . $name . " is " . $price . " yen.\n";
}
?>
Enter fullscreen mode Exit fullscreen mode

By using the $key => $value syntax, you gain direct access to the key within the loop. Choosing descriptive variable names (like $name and $price instead of $k and $v) is a pro-tip for keeping your code maintainable.


3. Reverse Lookup: array_search()

If you have a value and want to find its corresponding key, use array_search().

Important Limitation

<?php
$members = [101 => 'Suzuki', 102 => 'Tanaka', 103 => 'Yamada', 104 => 'Tanaka'];

// Search for the key where the value is 'Tanaka'
$id = array_search('Tanaka', $members);

var_dump($id); // int(102)
?>
Enter fullscreen mode Exit fullscreen mode

Caution: array_search() only returns the first matching key and then stops. In the example above, even though 'Tanaka' exists at ID 104, only 102 is returned. If no match is found, it returns false.


4. Modern Best Practices: First and Last Keys

Before PHP 7.3, getting the first or last key of an array required messy pointer manipulations. Now, we have dedicated functions that are both safe and fast.

array_key_first() and array_key_last()

<?php
$fruits = ['red' => 'Apple', 'yellow' => 'Banana', 'purple' => 'Grape'];

$firstKey = array_key_first($fruits); // 'red'
$lastKey  = array_key_last($fruits);  // 'purple'
?>
Enter fullscreen mode Exit fullscreen mode

These functions do not affect the internal array pointer, making them highly efficient for quick lookups at the boundaries of your data.


5. Checking for Existence: array_key_exists()

Before trying to retrieve or use a key, it’s often necessary to check if it actually exists.

Why not isset()?

While isset() is commonly used, it returns false if the key exists but the value is null. To strictly check for the presence of a key, always use array_key_exists().

<?php
$config = ['host' => 'localhost', 'pass' => null];

array_key_exists('pass', $config); // true
isset($config['pass']);            // false
?>
Enter fullscreen mode Exit fullscreen mode

Conclusion

Choosing the right array function depends on your specific needs:

  • Bulk extraction? Use array_keys().
  • Looping? Use foreach.
  • Reverse lookup? Use array_search().
  • Existence check? Use array_key_exists().

Mastering these basic but powerful tools is essential for any professional PHP developer aiming for clean and robust codebases.


Originally published at: [https://code-izumi.com/php/associative-array-keys/]

Top comments (0)