PHP array_keys() Tutorial 🎯

beginner
20 min

PHP array_keys() Tutorial 🎯

Welcome to CodeYourCraft's PHP array_keys() tutorial! In this lesson, we'll learn about the array_keys() function, a useful tool for working with PHP arrays. By the end of this lesson, you'll have a solid understanding of how to use this function to extract keys from an array, and you'll even get to practice with some examples! πŸ“

What is array_keys()? πŸ’‘

In PHP, array_keys() is a built-in function that returns an array containing the keys of the given input array. This function is particularly helpful when we need to work with the keys of an array separately from the values.

Syntax πŸ“

The syntax for array_keys() is quite straightforward:

php
array array_keys(array input_array)

Example: Basic Usage πŸ“

Let's start with a simple example to demonstrate the array_keys() function:

php
<?php $fruits = array( "apple" => 1, "banana" => 2, "orange" => 3 ); $fruitKeys = array_keys($fruits); print_r($fruitKeys); ?>

In this example, we have an associative array called $fruits, where the keys are the names of fruits, and the values are their respective IDs. When we call array_keys($fruits), we get an array containing the keys of the $fruits array:

Array ( [0] => "apple" [1] => "banana" [2] => "orange" )

πŸ’‘ Pro Tip: Remember that array_keys() returns the keys in the order they appear in the original array. If you need the keys in a specific order, consider sorting the array before using array_keys().

Advanced Example: Array Merge πŸ’‘

Now that we've covered the basics, let's take a look at a more advanced example where we'll use array_keys() to merge two arrays:

php
<?php $array1 = array( "fruit1" => "apple", "fruit2" => "orange", "fruit3" => "grape" ); $array2 = array( "fruit1" => "pear", "fruit4" => "banana", "fruit5" => "kiwi" ); $fruits = $array1 + $array2; $fruitKeys = array_keys($fruits); print_r($fruitKeys); ?>

In this example, we have two arrays $array1 and $array2. We use the + operator to merge these arrays. When we call array_keys($fruits) on the merged array, we get the keys of the resulting array:

Array ( [0] => "fruit1" [1] => "fruit2" [2] => "fruit3" [3] => "fruit4" [4] => "fruit5" )

Quiz πŸ’‘

Quick Quiz
Question 1 of 1

What does the `array_keys()` function do in PHP?

By now, you should have a good understanding of the array_keys() function in PHP! Remember to practice with some examples on your own to reinforce your understanding of this useful function. Happy coding! πŸ“ πŸš€