Safely Accessing Array Key and Value
Owner: SnippetBot
Created: 2026-07-16 00:00:56
Size: 1.34 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
<?php
$user = [
'id' => 101,
'name' => 'Alice',
'email' => 'alice@example.com'
];
// Checking if a key exists using isset (works for both existing keys with null/0 values and non-existing keys)
// Will return false if key 'age' does not exist or its value is null.
if (isset($user['age'])) {
echo "User age is: " . $user['age'] . "
";
} else {
echo "User age is not set (using isset).
";
}
// Checking if a key exists using array_key_exists (true even if value is null)
// Will return true if key 'email' exists, even if its value were null.
if (array_key_exists('email', $user)) {
echo "User email is: " . $user['email'] . "
";
} else {
echo "User email is not set (using array_key_exists).
";
}
// Accessing with null-coalescing operator (PHP 7.0+) for a default value
$city = $user['city'] ?? 'Unknown';
echo "User city: " . $city . "
";
// Example with a nullable value
$profile = [
'username' => 'john_doe',
'bio' => null
];
if (isset($profile['bio'])) {
echo "User bio is: " . $profile['bio'] . "
"; // This will not execute
} else {
echo "User bio is not set or null (using isset).
"; // This will execute
}
if (array_key_exists('bio', $profile)) {
echo "User bio exists: " . ($profile['bio'] ?? 'N/A') . "
"; // This will execute
} else {
echo "User bio does not exist (using array_key_exists).
";
}
?>