Code has been added to clipboard!

Understand How PHP Array Works and How to Handle It

Reading time 3 min
Published Aug 8, 2017
Updated Oct 2, 2019

As we went through the basics of PHP, we learned about different data types that are used to differentiate variables. One of them is the PHP array.

Unlike the most basic types (strings, integers, floats, and booleans), PHP arrays are considered to be compound variables. They are more complicated because one array can hold multiple different values. Therefore, they are useful for grouping values.

As PHP arrays are more complex than simple scalar data types, we will dedicate a bit more time to them. You will learn how to recognize and handle three different types of arrays, loop through them and use some common PHP array functions.

PHP Array: Main Tips

  • Arrays are used to contain more than one value in one variable.
  • Arrays allow you to avoid multiple unnecessary variables.
  • PHP Arrays index always start at 0.
  • There are 3 types of PHP arrays: indexed (numeric), associative (key names instead of index numbers) and multidimensional (contain other arrays).

Most Common Array Functions

First and foremost, you have to know the array() function. It defines the PHP array for a variable:

Example
<?php
   $fruits = array('Banana', 'Cherry', 'Peach');
?>

Then, there is count() function that counts all existing values in the PHP array. It can also be called getting PHP length of the array:

Example
<?php
   $fruits = array('Banana', 'Cherry', 'Peach');
   $array_length = count($fruits);
   echo $array_length;
?>

Indexed Arrays Explained

Indexed arrays are also called numeric (you could say they use integers as keys). Their values are stored in linear order. The index has to start with a zero and can only be a number. However, any type of values can be held.

Going through indexed arrays always requires defining its length. Remember it can always be retrieved using count() function.

Example
<?php
  $fruits = array('Banana', 'Cherry', 'Peach');
  echo $fruits[1];
?>

Learn to Loop Through Arrays

Using PHP arrays, we often have to use loops. They are meant for executing certain statements repeatedly, till the required result shows up. Let's see a few examples to get a better idea how that's done.

Indexed

To go through indexed array with a known length, you should use for loop. Using PHP echo array looping results are outputted to the screen:

Example
<?php
    $fruits = array('Banana', 'Cherry', 'Peach');
    $length = count($fruits);

    for($x = 0; $x < $length; $x++) {
        echo $fruits[$x];
        echo '<br>';
    }
?>

Associative

PHP associative array is different from indexed in that instead of integers it uses strings for keys. There is no linear order, and the developer is free to assign a specific key to any value they stored in the PHP array they created. Again, using PHP echo array loop results are displayed on the screen.

To go through a PHP associative array, you should use foreach loop:

Example
<?php
  $fruits = [
    'Banana' => 13, 
    'Cherry' => 134, 
    'Apple' => 21
  ];
  foreach ($fruits as $x => $x_value) { 
    echo "Key =" . $x . ", Value=" . $x_value;
    echo "<br>";
  }
?>

PHP Array: Summary

  • Arrays can be indexed, associative and multidimensional. All are used for holding multiple values in one variable.
  • The index of the array must start with a zero.
  • To make PHP loop through arrays, for and foreach should be used.
Tutorial
Introduction
Installation
Syntax
Variable
Superglobals
Data Types
String
Array
Multidimensional Array
Sort Array
Constant
Operators
Cookies
Sessions
DateTime
Error Handling
Exception Handling
File
Write and Create File
File Open, Read and Close
File Upload
Filtering
Redirecting
Advanced Filters
Forms
Form Required Field
Validate Email/URL
Form Validation
Form Action
Function
Prepared Statements
JSON
Calendar
ZIP File
FTP
HTTP Response
DateTime Functions
Error Functions
File Function
Filter
Math Functions
Mail Function
Miscellaneous Functions
Date Format
String Functions
Array Functions
Directory Functions
MySQL Database
MySQL Connection
MySQL Create Database
MySQL Create Table
MySQL Delete Data
MySQL Insert Data
MySQL Get Last Record ID
MySQL Insert Multiple Records
MySQL Select Data
MySQL Limit Data
MySQL Update Data
MySQLi Functions
AJAX and MySQL
AJAX Search
AJAX Poll
RSS Reader
Read XML File in PHP
XML Parser
SimpleXML Parser
SimpleXML: Node and Attribute
Expat XML Parser
DOMDocument
Libxml Functions
SimpleXML Functions
XML Parsing Functions
PHP isset
PHP echo and print
PHP if else and elseif
PHP switch case
PHP include File
PHP while Loop
PHP for and foreach
PHP mail()
PHP explode()
PHP substr()
PHP str_replace()
PHP array_push
PHP count()