All posts
PHPAugust 30, 20267 min read

PHP Arrays for Beginners: A Simple Guide

New to PHP arrays? Learn what they are, how to create indexed and associative arrays, and loop through them, with simple copy-paste examples.

F
Fepiq Team
Fepiq

If you searched for "PHP arrays for beginners," here is the short answer: a PHP array is a single variable that can hold many values at once, instead of you creating a separate variable for every value. This guide walks you through creating arrays, adding and removing items, looping over them, and the handful of array functions you will use every day, with small examples you can copy and run yourself.

What is an array in PHP?

Imagine you need to store the names of five students. Without an array, you would write five separate variables: $student1, $student2, and so on. That gets messy fast, and it is hard to loop over. An array solves this by storing all five names inside one variable, in order, so you can add, remove, count, and loop through them easily.

PHP has two main kinds of arrays you will use as a beginner: indexed arrays (items are numbered automatically, starting at 0) and associative arrays (items have names you choose, called keys). We will cover both.

Creating your first indexed array

An indexed array stores a list of values in order. PHP numbers each item for you automatically, starting from 0. Here is one holding three fruit names:

php
<?php
$fruits = ["apple", "banana", "cherry"];

echo $fruits[0]; // apple
echo $fruits[1]; // banana
echo $fruits[2]; // cherry
?>

Line by line: $fruits = [...] creates the array using square brackets, which is the modern way to write arrays in PHP (you may also see the older array(...) syntax; both work the same). Each value is separated by a comma. To read a value back out, you use the variable name followed by the position in square brackets, called the index. Remember that counting starts at 0, so $fruits[0] is "apple", not "banana".

Associative arrays: giving each item a name

Sometimes a number is not a useful way to refer to a value. An associative array lets you use a word (called a key) instead, which makes your code much easier to read.

php
<?php
$user = [
  "name" => "Maria",
  "email" => "maria@example.com",
  "age" => 27
];

echo $user["name"];  // Maria
echo $user["email"]; // maria@example.com
?>

Here, each item has a key on the left of the => arrow and a value on the right. "name", "email", and "age" are the keys. To get a value back, you use the key inside square brackets instead of a number, like $user["name"]. This is the pattern you will see constantly when PHP reads form data or database rows, since both naturally come as key-value pairs.

Looping through an array with foreach

Instead of writing $fruits[0], $fruits[1], and $fruits[2] by hand, you can use a foreach loop to visit every item automatically, even if the array has hundreds of items.

php
<?php
$fruits = ["apple", "banana", "cherry"];

foreach ($fruits as $fruit) {
  echo $fruit . "\n";
}
?>

foreach ($fruits as $fruit) means "for each value in $fruits, call it $fruit for this trip through the loop." Inside the curly braces {}, you can use $fruit just like any normal variable. The ."\n" adds a new line after each fruit so they print on separate lines.

For associative arrays, you can grab both the key and the value at the same time:

php
<?php
$user = ["name" => "Maria", "age" => 27];

foreach ($user as $key => $value) {
  echo $key . ": " . $value . "\n";
}
// name: Maria
// age: 27
?>

The as $key => $value part unpacks each pair, so on the first loop $key is "name" and $value is "Maria", then on the next loop $key is "age" and $value is 27.

Adding, removing, and counting items

Arrays are not fixed in size. You can add or remove items at any time while your script runs:

php
<?php
$fruits = ["apple", "banana"];

$fruits[] = "cherry";       // add to the end
unset($fruits[0]);          // remove "apple"
echo count($fruits);        // 2
?>

$fruits[] = "cherry" adds a new item to the end of the array without you needing to know the next index number. unset($fruits[0]) deletes the item at index 0. count($fruits) returns how many items are currently in the array, which is useful for showing totals or checking if an array is empty.

Here are the array functions you will reach for most often as a beginner:

FunctionWhat it doesExample
count($arr)Counts how many items are in the arraycount($fruits) → 2
array_push($arr, $v)Adds an item to the end (same as $arr[] = $v)array_push($fruits, "kiwi")
in_array($v, $arr)Checks if a value exists in the arrayin_array("apple", $fruits) → true or false
array_keys($arr)Returns all the keys as a new arrayarray_keys($user) → ["name", "age"]
sort($arr)Sorts the values and reindexes the arraysort($fruits)

Multidimensional arrays: arrays inside arrays

An array can hold other arrays as its values. This is called a multidimensional array, and it is exactly how PHP represents a list of records, such as several users or several products.

php
<?php
$users = [
  ["name" => "Maria", "age" => 27],
  ["name" => "John", "age" => 34]
];

foreach ($users as $user) {
  echo $user["name"] . " is " . $user["age"] . " years old\n";
}
?>

$users is an array containing two associative arrays. The outer foreach visits each inner array one at a time and calls it $user, so inside the loop $user["name"] and $user["age"] work exactly as they did in the earlier associative array example. This pattern is exactly what you will see later when a database query returns multiple rows.

Common beginner mistakes to avoid

  • Forgetting that indexed arrays start at 0, not 1, so the third item is $arr[2].
  • Mixing up = and => — use = to assign a variable and => only inside array key-value pairs.
  • Trying to read a key that does not exist, like $user["phone"] when it was never set, which triggers a warning. Check with isset($user["phone"]) first if you are not sure.
  • Forgetting the semicolon at the end of a line, including after the closing bracket of an array.
  • Using a foreach loop to change values without the & reference operator when you actually need to modify the original array.

Ready to fill an array with real data instead of typing it by hand? The next step is pulling rows straight from a database.

Learn how to connect PHP to a database

Frequently asked questions

What is the difference between an indexed array and an associative array in PHP?+

An indexed array numbers its items automatically starting from 0, so you access items by position, like $arr[0]. An associative array lets you choose a name (key) for each item instead, like $arr["name"], which makes the code easier to read when items have meaning.

How do I check if a key exists in a PHP array?+

Use isset($arr["key"]), which returns true if the key exists and its value is not null. For checking whether a key exists even if its value is null, use array_key_exists("key", $arr) instead.

How do I add an item to a PHP array?+

For an indexed array, use $arr[] = "value" to add it to the end. For an associative array, assign a new key directly, like $arr["newKey"] = "value". You can also use the array_push() function for indexed arrays.

Can a PHP array store different data types together?+

Yes. A single PHP array can mix strings, numbers, booleans, and even other arrays in the same array, since PHP does not require every item to be the same type. This is different from some other languages that only allow one type per array.

What is the difference between array() and square brackets []?+

They do exactly the same thing. array("a", "b") and ["a", "b"] create identical arrays. The square bracket syntax was added in PHP 5.4 and is now the more common style because it is shorter to type and read.

Arrays are one of the most-used building blocks in PHP. Once you are comfortable creating them, looping over them, and reading form or database data into them, most everyday PHP code will start to make a lot more sense.

Want help building a PHP application the right way from day one?

Talk to our team

Get new posts in your inbox

Occasional, no-fluff notes on shipping modern software — startups, automation, Laravel, Shopify and more. No spam, unsubscribe anytime.

Keep reading

Related posts

All posts

Let's build something

Ready to ship your next product with Fepiq?

Book a free discovery call. We'll listen, ask sharp questions, and send you a proposal within 3 business days.