PHP Array: Associative, Multidimensional

โšก Smart Summary

PHP Arrays store many related values inside a single variable, making related data easy to group and process. This walkthrough covers numeric, associative, and multidimensional arrays, the array comparison operators, and core functions such as count, sort, ksort, and asort.

  • ๐Ÿงฐ What Arrays Do: An array holds multiple related values in one variable, accessed by numeric or named keys instead of many separate variables.
  • ๐Ÿ”ข Numeric Arrays: Numeric arrays use integer index keys starting at zero to read or assign each stored element.
  • ๐Ÿท๏ธ Associative Arrays: Associative arrays use descriptive string keys, which is ideal for pairing names with values or mapping database fields.
  • ๐Ÿงฌ Multidimensional: A multidimensional array nests arrays inside an array, grouping structured data such as movies organized by category.
  • โš–๏ธ Array Operators: The union operator merges arrays, while == checks value equality and === also checks key order and data types.
  • ๐Ÿ”ง Array Functions: count, is_array, sort, ksort, and asort report on and reorder array contents by value or by key.
  • ๐Ÿค– AI Assist: AI tools can turn database rows into associative arrays and help debug confusing multidimensional array structures.

PHP Arrays

What is a PHP Array?

A PHP array is a variable that stores more than one piece of related data in a single variable.

Think of an array as a box of chocolates with slots inside.

The box represents the array itself, while the spaces containing chocolates represent the values stored in the array.

The examples below illustrate how this works.

Numeric Arrays

Numeric arrays use numbers as access keys.

An access key is a reference to a memory slot in an array variable.

The access key is used whenever we want to read or assign a new value to an array element.

Below is the syntax for creating a numeric array in PHP.

Array Example

<?php
$variable_name[n] = value;
?>

Or

<?php
$variable_name = array(n => value, ...);
?>

HERE,

  • “$variable_name…” is the name of the variable
  • “[n]” is the access index number of the element
  • “value” is the value assigned to the array element.

Let us now look at an example of a numeric array.

Suppose we have 5 movies that we want to store in array variables.

We can use the example shown below to do that.

<?php

$movie[0] = 'Shaolin Monk';
$movie[1] = 'Drunken Master';
$movie[2] = 'American Ninja';
$movie[3] = 'Once upon a time in China';
$movie[4] = 'Replacement Killers';

?>

Here,

PHP Array

Each movie is given an index number that is used to retrieve or modify its value. Observe the following code.

<?php
$movie[0]="Shaolin Monk";
$movie[1]="Drunken Master";
$movie[2]="American Ninja";
$movie[3]="Once upon a time in China";
$movie[4]="Replacement Killers";
echo $movie[3];
$movie[3] = " Eastern Condors";
echo $movie[3];
?>

Output:

Once upon a time in China Eastern Condors

As you can see from the above examples, working with arrays in PHP when dealing with multiple values of the same nature is very easy and flexible.

Alternatively, the above array variables can also be created using the following code.

<?php
$movie = array(0 => "Shaolin Monk",
1 => "Drunken Master",
2 => "American Ninja",
3 => "Once upon a time in China",
4 => "Replacement Killers" );
echo $movie[4];
?>

Output:

Replacement Killers

PHP Associative Array

Associative arrays differ from numeric arrays in the sense that associative arrays use descriptive names for id keys.

Below is the syntax for creating an associative array in PHP.

<?php
$variable_name['key_name'] = value;

$variable_name = array('keyname' => value);
?>

HERE,

  • “$variable_name…” is the name of the variable
  • “[‘key_name’]” is the access key of the element
  • “value” is the value assigned to the array element.

Let us suppose that we have a group of persons, and we want to assign the gender of each person against their names.

We can use an associative array to do that. The code below helps us to do that.

<?php
$persons = array("Mary" => "Female", "John" => "Male", "Mirriam" => "Female");
print_r($persons);
echo "";
echo "Mary is a " . $persons["Mary"];
?>

HERE,

PHP Array

Output:

Array ( [Mary] => Female [John] => Male [Mirriam] => Female ) Mary is a Female

Associative arrays are also very useful when retrieving data from the database.

The field names are used as id keys.

PHP Multi-dimensional arrays

These are arrays that contain other nested arrays.

The advantage of multidimensional arrays is that they allow us to group related data together.

Let us now look at a practical example that implements a PHP multidimensional array.

The table below shows a list of movies by category.

Movie title Category
Pink Panther Comedy
John English Comedy
Die Hard Action
Expendables Action
The Lord of the rings Epic
Romeo and Juliet Romance
See no evil hear no evil Comedy

The above information can be represented as a multidimensional array. The code below shows the implementation.

<?php
$movies = array(
"comedy" => array("Pink Panther", "John English", "See no evil hear no evil"),
"action" => array("Die Hard", "Expendables"),
"epic" => array("The Lord of the rings"),
"Romance" => array("Romeo and Juliet")
);
print_r($movies);
?>

HERE,

PHP Array

Output:

Array ( [comedy] => Array ( [0] => Pink Panther [1] => John English [2] => See no evil hear no evil ) [action] => Array ( [0] => Die Hard [1] => Expendables ) [epic] => Array ( [0] => The Lord of the rings ) [Romance] => Array ( [0] => Romeo and Juliet ) )

Another way to define the same array is as follows.

<?php
$film = array(
"comedy" => array(
0 => "Pink Panther",
1 => "John English",
2 => "See no evil hear no evil"
),
"action" => array (
0 => "Die Hard",
1 => "Expendables"
),
"epic" => array (
0 => "The Lord of the rings"
),
"Romance" => array
(
0 => "Romeo and Juliet"
)
);
echo $film["comedy"][0];
?>

Output:

Pink Panther

Note: the movies numeric array has been nested inside the categories associative array.

PHP Arrays: Operators

Operator Name Description How to do it Output
x + y Union Combines elements from both arrays
<?php
$x = array('id' => 1);

$y = array('value' => 10);

$z = $x + $y;
?>
Array([id] => 1 [value] => 10)
x == y Equal Compares two arrays and returns true if they are equal
<?php
$x = array("id" => 1);

$y = array("id" => "1");

if($x == $y)
{
echo "true";
}
else
{
echo "false";
}
?>
True or 1
x === y Identical Compares both the values and data types
<?php
$x = array("id" => 1);

$y = array("id" => "1");

if($x === $y)
{
echo "true";
}
else
{
echo "false";
}
?>
False or 0
x != y, x <> y Not equal Returns true if the two arrays are not equal
<?php
$x = array("id" => 1);

$y = array("id" => "1");

if($x != $y)
{
echo "true";
}
else
{
echo "false";
}
?>
False or 0
x !== y Non identical Returns true if the two arrays are not identical in value or type
<?php
$x = array("id" => 1);

$y = array("id" => "1");

if($x !== $y)
{
echo "true";
}
else
{
echo "false";
}
?>
True or 1

PHP Array Functions

Count function

The count function is used to count the number of elements that a PHP array contains. The code below shows the implementation.

<?php
$lecturers = array("Mr. Jones", "Mr. Banda", "Mrs. Smith");
echo count($lecturers);
?>

Output:

3

is_array function

The is_array function is used to determine if a variable is an array or not. Let us now look at an example that implements the is_array function.

<?php
$lecturers = array("Mr. Jones", "Mr. Banda", "Mrs. Smith");
echo is_array($lecturers);
?>

Output:

1

Sort

This function is used to sort arrays by their values.

If the values are alphanumeric, it sorts them in alphabetical order.

If the values are numeric, it sorts them in ascending order.

It removes the existing access keys and adds new numeric keys.

The output of this function is a numeric array.

<?php
$persons = array("Mary" => "Female", "John" => "Male", "Mirriam" => "Female");

sort($persons);

print_r($persons);
?>

Output:

Array ( [0] => Female [1] => Female [2] => Male )

ksort

This function is used to sort the array using the key. The following example illustrates its usage.

<?php
$persons = array("Mary" => "Female", "John" => "Male", "Mirriam" => "Female");

ksort($persons);

print_r($persons);
?>

Output:

Array ( [John] => Male [Mary] => Female [Mirriam] => Female )

asort

This function is used to sort the array using the values while keeping the keys. The following example illustrates its usage.

<?php

$persons = array("Mary" => "Female", "John" => "Male", "Mirriam" => "Female");

asort($persons);

print_r($persons);

?>

Output:

Array ( [Mary] => Female [Mirriam] => Female [John] => Male )

Why use arrays?

  • The contents of arrays can be stretched to hold more values.
  • Arrays easily help group related information such as server login details together.
  • Arrays help write cleaner code.

FAQs

The foreach loop is the most common way. Write foreach ($array as $value) to read each value, or foreach ($array as $key => $value) to read both the key and value of every element in the array.

sort() reorders values and reindexes the array with new numeric keys, losing the original keys. asort() sorts by value but keeps each value tied to its original key, which matters for associative arrays.

Use array_push() or $arr[] = value to append, and array_pop() or array_shift() to remove from the end or start. To delete a specific element by key, use the unset() function.

Yes. AI can write the fetch loop that maps each row into an associative array keyed by column name, and suggest using fetch methods that return associative arrays directly from your database driver.

Yes. Paste the print_r or var_dump output, and AI can explain the nesting, show the exact path to a value such as $film[‘comedy’][0], and spot mismatched keys or levels.

Summarize this post with: