PHP arrays are powerful data structures to store multiple values in a single variable.
- Understand the difference between indexed and associative arrays and when to use each.
- Access, modify, and traverse array elements, including nested arrays.
- Apply common built-in array functions (
count(),sort(),explode(),in_array(), etc.). - Handle arrays safely — validate keys, use strict comparisons, and never trust request data.
An indexed array is an ordered collection where keys are integers starting from 0.
array.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Indexed Arrays</title>
</head>
<body>
<?php
$array1 = array(4, 5, 6, 7, 21, 34, 56, 77, 2);
echo $array1[1]; // Output: 5
echo "<br />";
echo $array1[0]; // Output: 4
// Modify array element
$array1[0] = 99;
echo "<br />";
echo $array1[0]; // Output: 99
// Array with mixed data
$array2 = array(88, "Rahul", "Jain", array("a", "b", "c"));
echo "<br />";
echo $array2[0]; // Output: 88
echo "<br />";
echo $array2[1] . " " . $array2[2]; // Output: Rahul Jain
echo "<br />";
// Nested array access
echo $array2[3][0]; // Output: a
echo "<br />";
echo $array2[3][1]; // Output: b
echo "<br />";
echo $array2[3][2]; // Output: c
echo "<br />";
// User info array
$user = array(1, "Rahul", "Jain", "rahul@armour.com", "password1");
echo $user[3]; // Output: rahul@armour.com
?>
</body>
</html>An associative array uses named keys (strings) instead of numeric indexes.
associative_array.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Associative Arrays</title>
</head>
<body>
<?php
// Normal indexed array
$user = array(1, "Rahul", "Jain", "rahul@armour.com", "password1");
print_r($user);
echo "<br />" . $user[3] . "<br />";
// Associative array
$user2 = array(
'id' => 1,
'f_name' => "Rahul",
'l_name' => "Jain",
'email' => "rahul@armour.com",
'password' => "password1"
);
print_r($user2);
echo "<br />" . $user2['email'] . "<br />";
echo $user2['password'] . "<br />";
// Combining values
$user_full_name = $user2["f_name"] . " " . $user2["l_name"];
echo $user_full_name . "<br />";
$user_email = $user2["email"];
echo $user_email;
?>
</body>
</html>PHP provides many built-in functions to work with arrays.
array_functions.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Array Functions</title>
</head>
<body>
<?php
$array1 = array(41, 34, 2, 35, 12, 65, 8, 9, 45);
?>
Count: <?= count($array1); ?> <br />
Max value: <?= max($array1); ?> <br />
Min value: <?= min($array1); ?> <br />
<?php
print_r($array1);
?>
<br />
Sort:
<?php
sort($array1);
print_r($array1);
?>
<br />
Reverse Sort:
<?php
rsort($array1);
print_r($array1);
?>
<br />
Explode:
<?php
$str3 = "This is a demo";
$array3 = explode(" ", $str3);
print_r($array3);
?>
<br />
Implode (space):
<?php
$str1 = implode(" ", $array1);
echo $str1;
?>
<br />
Implode (comma):
<?php
$str2 = implode(",", $array1);
echo $str2;
?>
<br />
In Array (check if 45 exists):
<?php
$int1 = in_array(45, $array1);
echo $int1 ? "Found" : "Not Found";
echo "<br />";
echo gettype($int1); // boolean
?>
</body>
</html>| Function | Description |
|---|---|
count() |
Count number of elements in an array |
max() |
Find maximum value |
min() |
Find minimum value |
sort() |
Sort an array (ascending) |
rsort() |
Sort an array (descending) |
explode() |
Split a string into an array |
implode() |
Join array elements into a string |
in_array() |
Check if a value exists in an array |
-
Always validate array keys before accessing them to avoid warnings.
-
Use associative arrays when working with structured data (like user records).
-
Prefer using array functions for better performance and cleaner code.
When working with arrays:
-
print_r($array);is great for quick debugging. -
var_dump($array);gives detailed type and value information.
-
Accessing an undefined key (e.g.
$array[10]when it does not exist) raises a warning in PHP 8+. Guard withisset()orarray_key_exists()first. -
Assuming
sort()preserves keys —sort()andrsort()reindex the array. Useasort()/ksort()when you need to keep associative key–value pairs aligned. -
Relying on the default loose comparison of
in_array()—in_array(0, ["abc"])returnstruedue to type juggling. Passtrueas the third argument for strict matching.
-
Never store secrets in plaintext — the example arrays above use
'password' => "password1"for illustration only. Real credentials must be hashed withpassword_hash()before storage and verified withpassword_verify(). -
Treat request data as untrusted — values from
$_GET,$_POST, or$_REQUESTused as array keys or values should be validated and sanitized before use to avoid injection and logic-abuse bugs. -
Use strict
in_array()checks on security-relevant lookups (allowlists, role checks):in_array($needle, $haystack, true)prevents type-juggling bypasses. -
Do not concatenate array data into SQL — when array values reach a database, always bind them through PDO prepared statements rather than building query strings.
- Indexed arrays use integer keys starting at
0; associative arrays use named string keys for structured data. - Arrays can nest, letting you model records and collections in a single variable.
- Built-in functions cover most needs — counting, sorting, splitting/joining, and membership tests.
- Treat array data as untrusted where it comes from user input: validate keys, use strict
in_array(), hash secrets, and bind values through PDO prepared statements before they reach SQL.
-
Multidimensional Arrays
-
Array Iteration (
foreach,for, etc.) -
Advanced Array Functions (
array_map(),array_filter(),array_reduce())
- PHP-Data-Types — arrays are one of PHP's core data types
- Array-Pointers — internal pointer used to traverse arrays
- Foreach-Loops — primary way to iterate over array elements
- Secure PHP Development — language hub