PHP Array Functions I
PHP provides dozens of built-in array functions. In this lesson, we'll cover the essential functions for counting, searching, and extracting information from arrays.
Counting Elements
| Function | Description |
|---|---|
count($arr) |
Returns number of elements in array |
sizeof($arr) |
Alias for count() |
count($arr, COUNT_RECURSIVE) |
Counts all elements including nested arrays |
<?php
$fruits = ["Apple", "Banana", "Cherry"];
echo count($fruits); // 3
$nested = ["a", ["b", "c"], "d"];
echo count($nested); // 3 (top level only)
echo count($nested, COUNT_RECURSIVE); // 5 (all elements)
// Empty array check
$empty = [];
if (count($empty) === 0) {
echo "Array is empty";
}
?>
Output
Click Run to execute your code
Checking for Values
in_array()
Check if a value exists in an array:
<?php
$fruits = ["Apple", "Banana", "Cherry"];
// Basic usage
in_array("Banana", $fruits); // true
in_array("Grape", $fruits); // false
// Case-sensitive!
in_array("apple", $fruits); // false
in_array("Apple", $fruits); // true
// Strict mode (checks type too)
$mixed = [1, 2, "3", 4];
in_array(3, $mixed); // true (loose comparison)
in_array(3, $mixed, true); // false (strict comparison)
in_array("3", $mixed, true); // true
?>
Best Practice: Use the third parameter
true for strict
comparison to avoid unexpected matches due to type juggling.
Finding Keys
array_search()
Find the key of a value:
<?php
$fruits = ["apple", "banana", "cherry"];
// Find key
$key = array_search("banana", $fruits);
echo $key; // 1
// Not found returns false
$key = array_search("grape", $fruits);
if ($key === false) {
echo "Not found";
}
// With duplicates, returns first match
$items = ["a", "b", "c", "b"];
echo array_search("b", $items); // 1 (first occurrence)
?>
Important: Always use
=== false to check for "not found"
because array_search() can return 0 (a valid key), which is falsy!
Checking for Keys
array_key_exists() vs isset()
| Function | Returns true for null values? | Use when |
|---|---|---|
array_key_exists() |
Yes | Need to know if key exists regardless of value |
isset() |
No | Need to know if key exists AND is not null |
<?php
$data = [
"name" => "John",
"email" => null,
"active" => false
];
// array_key_exists - checks only if key exists
array_key_exists("name", $data); // true
array_key_exists("email", $data); // true (even though null)
array_key_exists("phone", $data); // false
// isset - checks if key exists AND is not null
isset($data["name"]); // true
isset($data["email"]); // false (null value)
isset($data["phone"]); // false
?>
Extracting Keys and Values
array_keys()
<?php
$person = ["name" => "John", "age" => 30, "city" => "NYC"];
// Get all keys
$keys = array_keys($person);
print_r($keys); // ["name", "age", "city"]
// Get keys for specific value
$scores = ["Alice" => 95, "Bob" => 88, "Carol" => 95];
$topScorers = array_keys($scores, 95);
print_r($topScorers); // ["Alice", "Carol"]
?>
array_values()
<?php
$person = ["name" => "John", "age" => 30, "city" => "NYC"];
// Get all values (reindexed)
$values = array_values($person);
print_r($values); // ["John", 30, "NYC"]
// Useful for reindexing after unset
$arr = [0 => "a", 1 => "b", 2 => "c"];
unset($arr[1]);
print_r($arr); // [0 => "a", 2 => "c"] - gap in indices
$arr = array_values($arr);
print_r($arr); // [0 => "a", 1 => "c"] - reindexed
?>
First and Last Elements
<?php
$queue = ["first", "second", "third", "last"];
// Get first element
$first = reset($queue); // "first" (moves pointer to start)
// Get last element
$last = end($queue); // "last" (moves pointer to end)
// Get current element
$current = current($queue); // "last" (pointer is at end)
// PHP 7.3+: Get first/last key without moving pointer
$firstKey = array_key_first($queue); // 0
$lastKey = array_key_last($queue); // 3
?>
Practical Examples
<?php
// Check if user role is allowed
$allowedRoles = ["admin", "editor", "moderator"];
$userRole = "editor";
if (in_array($userRole, $allowedRoles, true)) {
echo "Access granted";
}
// Find user by email
$users = [
["id" => 1, "email" => "[email protected]"],
["id" => 2, "email" => "[email protected]"],
["id" => 3, "email" => "[email protected]"]
];
$searchEmail = "[email protected]";
$foundUser = null;
foreach ($users as $user) {
if ($user["email"] === $searchEmail) {
$foundUser = $user;
break;
}
}
// Get unique values
$tags = ["php", "javascript", "php", "python", "javascript"];
$uniqueTags = array_unique($tags);
print_r($uniqueTags); // ["php", "javascript", "python"]
?>
Quick Reference
| Task | Function |
|---|---|
| Count elements | count($arr) |
| Check if value exists | in_array($val, $arr) |
| Find key of value | array_search($val, $arr) |
| Check if key exists | array_key_exists($key, $arr) |
| Get all keys | array_keys($arr) |
| Get all values | array_values($arr) |
| Remove duplicates | array_unique($arr) |
| Get first element | reset($arr) |
| Get last element | end($arr) |
Exercise: Search System
Task: Build a simple product search system.
Requirements:
- Create an array of products with id, name, category, price
- Function to find product by ID
- Function to check if category exists
- Function to get all unique categories
- Function to count products per category
Show Solution
<?php
$products = [
["id" => 1, "name" => "Laptop", "category" => "Electronics", "price" => 999],
["id" => 2, "name" => "Mouse", "category" => "Electronics", "price" => 29],
["id" => 3, "name" => "Desk", "category" => "Furniture", "price" => 199],
["id" => 4, "name" => "Chair", "category" => "Furniture", "price" => 149],
["id" => 5, "name" => "Notebook", "category" => "Stationery", "price" => 5]
];
// Find product by ID
function findProductById($products, $id) {
foreach ($products as $product) {
if ($product["id"] === $id) {
return $product;
}
}
return null;
}
// Check if category exists
function categoryExists($products, $category) {
foreach ($products as $product) {
if ($product["category"] === $category) {
return true;
}
}
return false;
}
// Get unique categories
function getCategories($products) {
$categories = [];
foreach ($products as $product) {
if (!in_array($product["category"], $categories)) {
$categories[] = $product["category"];
}
}
return $categories;
}
// Count products per category
function countByCategory($products) {
$counts = [];
foreach ($products as $product) {
$cat = $product["category"];
if (!isset($counts[$cat])) {
$counts[$cat] = 0;
}
$counts[$cat]++;
}
return $counts;
}
// Test the functions
echo "Product #2: ";
print_r(findProductById($products, 2));
echo "Electronics exists: " . (categoryExists($products, "Electronics") ? "Yes" : "No") . "\n";
echo "Categories: " . implode(", ", getCategories($products)) . "\n";
echo "Products per category:\n";
print_r(countByCategory($products));
?>
Summary
- count(): Get array length
- in_array(): Check if value exists (use strict mode!)
- array_search(): Find key of a value (returns false if not found)
- array_key_exists(): Check if key exists (works with null values)
- isset(): Check if key exists AND is not null
- array_keys(): Extract all keys as a new array
- array_values(): Extract all values (reindexes array)
- array_unique(): Remove duplicate values
What's Next?
Now let's explore Array Functions II - functions for modifying arrays: adding, removing, merging, and slicing elements!
Enjoying these tutorials?