What you'll learn
Quick Answer
PHP arrays store many values in one variable. Indexed arrays use numeric positions, associative arrays use named keys, and multidimensional arrays nest arrays inside other arrays. You loop over them with foreach and manage them with built-in functions like count(), array_push(), array_map(), sort(), and in_array().
What Are PHP Arrays?
An array in PHP is a single variable that holds many values at once. Instead of creating $student1, $student2, and $student3, you keep everything in one place and reach each value by its key. If you are learning back-end development, PHP arrays are one of the first tools you will use every single day.
PHP gives you three common ways to organise array data:
| Type | Keys | Best for |
|---|---|---|
| Indexed | Numbers (0, 1, 2...) | Simple lists |
| Associative | Named strings | Records with fields |
| Multidimensional | Arrays inside arrays | Tables and nested data |
Under the hood all three are the same thing: a PHP array is an ordered map that links keys to values. The three names simply describe how you use it.
Indexed Arrays
An indexed array is a plain list. PHP gives each value a number automatically, starting at 0.
$fruits = ["apple", "banana", "mango"];
echo $fruits[0]; // apple
echo $fruits[2]; // mango
The modern [] syntax (PHP 5.4 and newer) does the same job as the older array() form, so $fruits = array("apple", "banana") also works. Stick with []. It is shorter and it is what you will see in most code today.
You can set positions by hand too, but be careful: skipping numbers leaves gaps.
$scores = [];
$scores[0] = 90;
$scores[1] = 75;
$scores[5] = 60; // keys 2, 3 and 4 simply do not exist
Associative Arrays
An associative array uses your own named keys instead of numbers. This is perfect for a single record, such as one student.
$student = [
"name" => "Priya",
"age" => 20,
"city" => "Pune",
];
echo $student["name"]; // Priya
echo $student["city"]; // Pune
The => symbol links a key to its value. Keys are usually strings, and each key must be unique. If you repeat a key, the last value silently wins.
Named keys make your code readable. $student["age"] tells you exactly what the value means, while $student[1] forces the reader to guess.
Multidimensional Arrays
A multidimensional array is an array whose values are themselves arrays. This is how you store a table, like a full list of students where each one has several fields.
$students = [
["name" => "Priya", "marks" => 88],
["name" => "Rahul", "marks" => 72],
["name" => "Aisha", "marks" => 95],
];
echo $students[0]["name"]; // Priya
echo $students[2]["marks"]; // 95
Read the keys left to right: the first bracket picks the row and the second bracket picks the field in that row. So $students[2]["marks"] means "third student, marks value". You can nest as deep as you need, but two levels covers most real work.
Adding and Removing Elements
Arrays are not fixed in size. You can grow or shrink them at any time.
$fruits = ["apple", "banana"];
$fruits[] = "mango"; // append to the end
array_push($fruits, "grape"); // same idea, can add several at once
$student = ["name" => "Priya"];
$student["city"] = "Pune"; // add a new named key
// removing
array_pop($fruits); // remove the last item
array_shift($fruits); // remove the first item
unset($student["city"]); // remove one key
Gotcha: using unset() on an indexed array removes the value but does not renumber the remaining keys, so you can end up with keys like 0, 1, 3. If you need a clean 0, 1, 2 sequence again, run $fruits = array_values($fruits);.
Looping With foreach
The foreach loop is the cleanest way to walk through an array. For an indexed array you just grab each value:
$fruits = ["apple", "banana", "mango"];
foreach ($fruits as $fruit) {
echo $fruit . "\n";
}
For an associative array you can grab the key and the value together:
$student = ["name" => "Priya", "city" => "Pune"];
foreach ($student as $key => $value) {
echo "$key: $value\n";
}
For a multidimensional array, loop over the rows and read each field by its key:
foreach ($students as $s) {
echo $s["name"] . " scored " . $s["marks"] . "\n";
}
Prefer foreach over a manual for loop with a counter. It works for both indexed and associative arrays and never runs off the end of the array.
Essential Array Functions
PHP ships with hundreds of array functions. These five cover most beginner tasks:
count()gives the number of items.in_array()checks if a value exists.sort()puts values in order.array_map()transforms every value into a new array.array_push()adds items to the end.
$numbers = [5, 2, 9, 1];
count($numbers); // 4
in_array(9, $numbers); // true
sort($numbers); // $numbers is now [1, 2, 5, 9]
$doubled = array_map(function ($n) {
return $n * 2;
}, $numbers); // [2, 4, 10, 18]
Gotcha: sort() changes the original array in place and returns only true or false. Never write $numbers = sort($numbers), or you will overwrite your data with true. Also note that sort() throws away the keys and renumbers from 0, so for associative arrays use asort() (keeps keys, sorts by value) or ksort() (sorts by key) instead.
A Real Example: Reading Form Data
Here is where arrays click for most learners. When a user submits an HTML form, PHP hands you the data as an associative array in $_POST (or $_GET). The name of each field becomes the key.
<form method="post" action="signup.php">
<input type="text" name="name">
<input type="email" name="email">
<input type="checkbox" name="skills[]" value="php"> PHP
<input type="checkbox" name="skills[]" value="sql"> SQL
<button>Sign up</button>
</form>
In signup.php you read those keys straight out of $_POST:
$name = $_POST["name"] ?? "";
$email = $_POST["email"] ?? "";
$skills = $_POST["skills"] ?? []; // an indexed array of ticked boxes
echo "Name: $name\n";
echo "You picked " . count($skills) . " skills.\n";
foreach ($skills as $skill) {
echo "- $skill\n";
}
Two things to notice. The ?? (null coalescing) operator supplies a safe default so you never hit an "undefined index" warning when a field is empty. And the [] in name="skills[]" tells PHP to collect every ticked checkbox into one array. Want to build the full sign-up page, database, and validation around this? Our free PHP course walks through it step by step.
Common Mistakes and a Recommendation
A few traps catch almost every beginner:
- Undefined key warnings. Reading
$data["phone"]when that key is missing throws a warning. Guard it with$data["phone"] ?? "", or check first withisset()orarray_key_exists(). - Loose value matching. By default
in_array("1", [1, 2, 3])istruebecause PHP compares loosely. Pass a third argument to force a strict, type-aware check:in_array("1", [1, 2, 3], true)isfalse. - Value vs key. Use
in_array()to search for a value, butarray_key_exists()to check for a key. They are not interchangeable.
Recommendation: reach for an associative array whenever your data has named fields, use a multidimensional array for lists of those records, and loop with foreach almost every time. Master these patterns and you have the foundation for reading form input, working with databases, and building real PHP applications.
Frequently Asked Questions
What is the difference between indexed and associative arrays in PHP?
An indexed array uses automatic numeric keys starting at 0, which suits simple lists like ["apple", "banana"]. An associative array uses your own named string keys, like ["name" => "Priya"], which is better for a record with clearly labelled fields. Internally both are the same ordered map; the difference is just whether the keys are numbers or names.
How do I count the number of elements in a PHP array?
Use the built-in count() function, for example count($fruits). It returns the number of top-level items. For a multidimensional array, count() counts the rows, not the values inside each row. If you need a full recursive total, pass the second argument: count($data, COUNT_RECURSIVE).
Does sort() return a new sorted array?
No. sort() sorts the array in place and returns only true or false. So you write sort($numbers); and then use $numbers directly. Never write $numbers = sort($numbers), because that overwrites your data with the boolean true. To keep the original and get a sorted copy, clone it first, then sort the copy.
How do I check if a value exists in a PHP array?
Use in_array($value, $array) to check for a value and array_key_exists($key, $array) to check for a key. Add true as a third argument to in_array() for a strict, type-safe comparison so that a string "1" does not match the integer 1.
How does PHP turn form fields into an array?
When a form is submitted, PHP builds an associative array in $_POST (for POST forms) or $_GET, where each field's name becomes the key. If you name a group of inputs with brackets, like name="skills[]", PHP collects all of their values into one indexed array under that key, which is ideal for checkboxes and multi-select lists.
Should beginners use array() or the [] syntax?
Use the short [] syntax. It has been available since PHP 5.4, does exactly the same thing as array(), and is what you will see in almost all modern code and tutorials. The older array() form still works, so you can read it in legacy projects, but there is no reason to write new code with it.
