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
EasyRead 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:
- Check if
key1exists in the array. If it does, print the value associated with it. If not, printKey not found. - Check if
key2exists in the array. If it does, print the value associated with it. If not, printKey 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 foundIf the inputs are {"title": "Manager", "department": "Sales"}, salary, and department, the output should be:
Key not found
SalesCheat 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"
?>This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Comparison & Logical Operators
Comparison OperatorsEquality & IdentityLogical Operators Part 1Logical Operators Part 2Recap - Simple Logic7Arrays Part 2 - Associative
Intro to Associative ArraysAccessing Values by KeyModifying Values by KeyAdding New Key-Value PairsCheck if Key ExistsRecap - Key-Value Data Store2Variables and Data Types
NumbersStrings and QuotesBooleansNaming ConventionsRecap - Variable InitEmpty VariablesString ConcatenationGetting User InputCast to Different Types5Conditional Logic
If StatementIf - ElseThe Ternary OperatorNull Coalescing OperatorSwitch StatementRecap - Making Decisions3Basic Operators
Arithmetic OperatorsModulo OperatorExponentiation OperatorCombined AssignmentIncrement/DecrementOperator PrecedenceRecap - Simple CalculationsString Operators