Menu
Coddy logo textTech

Check if Key Exists

Part of the Fundamentals section of Coddy's PHP journey — lesson 45 of 71.

When working with associative arrays, you'll often need to check whether a specific key exists before trying to access its value. Attempting to access a non-existent key can cause errors, so PHP provides the array_key_exists() function to safely check first.

<?php
$person = [
    "name" => "Alice",
    "age" => 25
];

if (array_key_exists("name", $person)) {
    echo "Name exists!";
}

if (array_key_exists("city", $person)) {
    echo "City exists!";
} else {
    echo "City not found";
}
?>

The function takes two arguments: the key you're looking for and the array to search in. It returns true if the key exists, and false otherwise. This makes it perfect for use in conditional statements.

This check is especially useful when dealing with data that might be incomplete—like user input or data from external sources—where you can't guarantee all expected keys are present.

challenge icon

Challenge

Easy

Read a line of input containing a JSON object representing user data (e.g., {"username": "john_doe", "email": "john@example.com", "age": 28}).

Then read two more inputs:

  • A string key1 - the first key to check
  • A string key2 - the second key to check

Create an associative array from the JSON input, then:

  1. Check if key1 exists in the array. If it does, print the value associated with it. If not, print Key not found.
  2. Check if key2 exists in the array. If it does, print the value associated with it. If not, print Key not found.

Print each result on a separate line.

Example:

If the inputs are {"username": "john_doe", "email": "john@example.com", "age": 28}, username, and phone, the output should be:

john_doe
Key not found

If the inputs are {"title": "Manager", "department": "Sales"}, salary, and department, the output should be:

Key not found
Sales

Cheat sheet

Use array_key_exists() to check if a specific key exists in an associative array before accessing it:

<?php
$person = [
    "name" => "Alice",
    "age" => 25
];

if (array_key_exists("name", $person)) {
    echo "Name exists!";
}

if (array_key_exists("city", $person)) {
    echo "City exists!";
} else {
    echo "City not found";
}
?>

The function takes two arguments: the key to search for and the array. It returns true if the key exists, false otherwise.

Try it yourself

<?php
// Read the JSON input
$jsonInput = trim(fgets(STDIN));
$key1 = trim(fgets(STDIN));
$key2 = trim(fgets(STDIN));

// Convert JSON to associative array
$userData = (array)json_decode($jsonInput, true);

// TODO: Write your code below
// Check if key1 exists and print the value or "Key not found"

// Check if key2 exists and print the value or "Key not found"

?>
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals