• Home
  • HTML
    • HTML Introduction
    • HTML Basic
    • HTML Elements
    • HTML Attributes
    • HTML Headings
    • HTML Paragraphs
    • HTML Text Formatting
    • HTML Styles
    • HTML Comments
    • HTML Styles - CSS
    • HTML Links
    • HTML Images
    • HTML Tables
    • HTML Lists
    • HTML Block and Inline Elements
    • HTML class Attribute
    • HTML Forms
    • HTML Media
  • CSS
    • Introduction of CSS
    • CSS Syntax
    • CSS Selectors
    • How To Add CSS
    • CSS Comments
    • CSS Colors
    • CSS Backgrounds
    • CSS Borders
    • CSS Margins
    • CSS Text
    • CSS Lists
    • CSS Tables
    • CSS Box Model
    • CSS Dimension
    • CSS Padding
    • CSS Border
    • CSS Margin
    • CSS Outline
    • CSS Cursors
    • CSS Overflow
    • CSS Units
    • CSS Visual Formatting
    • CSS Display
    • CSS Visibility
    • CSS Position
    • CSS Layers
    • CSS Float
    • CSS Alignment
    • CSS Pseudo-classes
    • CSS Pseudo-elements
    • CSS Media Types
    • CSS Sprites
    • CSS Opacity
    • CSS Attribute Selectors
    • CSS Validation
    • CSS3 Border
    • CSS3 Gradients
    • CSS3 Text Overflow
  • JavaScript
    • JS Introduction
    • JS Getting Started
    • JS Syntax
    • JS Variables
    • JS Generating Output
    • JS Data Types
    • JS Operators
    • JS Events
    • JS Strings
    • JS Numbers
    • JS If Else
    • JS Switch Case
    • JS Arrays
    • JS Sorting Arrays
    • JS Loops
    • JS Functions
    • JS Objects
    • JS DOM Nodes
    • JS DOM Selectors
    • JS DOM Styling
    • JS DOM Get Set Attributes
    • JS DOM Manipulation
    • JS DOM Navigation
    • JS Window
    • JS Screen
    • JS Location
    • JS History
    • JS Navigator
    • JS Dialog Boxes
    • JS Timers
    • JS Date and Time
    • JS Math Operations
    • JS Type Conversions
    • JS Event Listeners
    • JS Event Propagation
    • JS Borrowing Methods
    • JS Hoisting Behavior
    • JS Closures
    • JS Strict Mode
    • JS JSON Parsing
    • JS Error Handling
    • JS Regular Expressions
    • JS Form Validation
    • JS Cookies
    • JS AJAX Requests
    • JS ES6 Features
  • jQuery
    • jQuery Introduction
    • jQuery Syntax
    • jQuery Selectors
    • jQuery Events
    • jQuery Show/Hide
    • jQuery Fade
    • jQuery Slide
    • jQuery Animation
    • jQuery Stop
    • jQuery Chaining
    • jQuery Callback
    • jQuery Get/Set
    • jQuery Insert
    • jQuery Remove
    • jQuery CSS Classes
    • jQuery Style Properties
    • jQuery Dimensions
    • jQuery Traversing
    • jQuery Ancestors
    • jQuery Descendants
    • jQuery Siblings
    • jQuery Filtering
    • jQuery Ajax
    • jQuery Load
    • jQuery Get/Post
    • jQuery No-Conflict
  • PHP
    • PHP Introduction
    • PHP Install
    • PHP Syntax
    • PHP Comments
    • PHP Variables
    • PHP Echo / Print
    • PHP Data Types
    • PHP Strings
    • PHP Constants
    • PHP Operators
    • PHP If...Else...Elseif
    • PHP Switch
    • PHP Loops
    • PHP Functions
    • PHP Arrays
    • PHP Superglobals
    • PHP Date and Time
    • PHP Include
    • PHP File Handling
    • PHP File Upload
    • PHP Cookies
    • PHP Sessions
    • PHP Filters
    • PHP Callback Functions
    • PHP JSON
    • PHP Exceptions
    • PHP What is OOP
    • PHP Classes/Objects
    • PHP Constructor
    • PHP Destructor
    • PHP Access Modifiers
    • PHP Inheritance
    • PHP Abstract Classes
    • PHP Interfaces
    • PHP Traits
    • PHP Static Methods
    • PHP Namespaces
  • SQL
    • Introduction to SQL
    • SQL Create Command
    • SQL ALTER Command
    • SQL Truncate Drop Rename
    • INSERT SQL command
    • UPDATE SQL command
    • DELETE SQL command
    • SQL COMMIT command
    • SQL ROLLBACK command
    • SQL GRANT and REVOKE Command
    • SQL WHERE clause
    • SQL LIKE clause
    • SQL ORDER BY Clause
    • SQL Group By Clause
    • SQL HAVING Clause
    • SQL DISTINCT keyword
    • SQL AND OR operator
    • SQL Constraints
    • SQL Functions
    • SQL JOIN
  • Python
    • Getting started with Python
    • Introduction to IDLE
    • Python 2.x vs. Python 3.x
    • Syntax Rules and First Program
    • Numbers and Math Functions
    • Python Operators
    • Python Variables
    • Python Modules and Functions
    • Python Input and Output
    • Data Types in Python
    • String in Python
    • String Functions in python
    • Lists in Python
    • Utilizing List Elements by Iterating
    • Deleting List Elements & other Functions
    • Dictionaries in Python
    • Functions for Dictionary
    • Tuples in Python
    • Relational and Logical Operators
    • Conditional Statements in Python
    • Looping in Python
    • Define Functions in Python
    • Python-Introduction to OOP
    • Object Oriented Programming in Python
    • Classes in Python
    • The concept of Constructor
    • Destructors - Destroying the Object in Python
    • Inheritance in Python
    • Access Modifers in Python
    • Types of Inheritance
    • Method Overriding in Python
    • Polymorphism
    • static Keyword
    • Operator Overloading Python
    • Introduction to Error Handling
    • Exception Handling: try and except
    • Exeption Handling: finally
    • Exception Handling: raise
    • File Handling
    • Reading and Writing File
    • Introduction to Multithreading
    • Threading Module in Python
    • Thread Object
    • Lock Object
    • RLock Object
    • Event Object
    • Timer Object
    • Condition Object
    • Barrier Object
    • __name__ Variable in Python
    • Iterable and Iterator
    • yield Keyword
    • Python Generators
    • Python Closures
    • Python Decorators
    • @property Decorator in Python
    • Assert Statement
    • Garbage Collection
    • Shallow and Deep Copy
    • Introduction to Logging
    • Configure Log LEVEL, Format etc
    • Python Logging in a file
    • Python Logging Variable Data
    • Python Logging Classes and Functions
    • Python MySQL Introduction
    • Create Database - Python MySQL
    • Create Table - Python MySQL
    • Insert Data in Table
    • Select Data from Table
    • Update data in Table
    • Delete data from Table
    • Drop Table from Database
    • WHERE clause - Python MySQL
    • Order By clause - Python MySQL
    • Limit clause - Python MySQL
    • Table Joins - Python MySQL
  • MongoDB
    • MongoDB Introduction
    • Overview of MongoDB
    • MongoDB vs SQL Databases
    • Advantages of MongoDB
    • When to go for MongoDB
    • Data Modelling in MongoDB
    • Is MongoDB really Schemaless?
    • Installing MongoDB on Windows and Linux
    • Datatypes in MongoDB
    • Create and Drop Database in MongoDB
    • MongoDB: Creating a Collection
    • CRUD Operations in MongoDB
    • Data Relationships in MongoDB
    • Indexing in MongoDB
    • Sorting in MongoDB
    • Aggregation in MongoDB
    • Data Backup and Restoration in MongoDB
    • Sharding in MongoDB
    • Java Integration with MongoDB
  • Elixir
    • Elixir Overview
    • Elixir Environment
    • Elixir Basic Syntax
    • Elixir Data Types
    • Elixir Variables
    • Elixir Operators
    • Elixir Pattern Matching
    • Elixir Decision Making
    • Elixir Strings
    • Elixir Char Lists
    • Elixir Lists and Tuples
    • Elixir Keyword Lists
    • Elixir Maps
    • Elixir Modules
    • Elixir Aliases
    • Elixir Functions
    • Elixir Recursion
    • Elixir Loops
    • Elixir Enumerables
    • Elixir Streams
    • Elixir Structs
    • Elixir Protocols
    • Elixir File I/O
    • Elixir Processes
    • Elixir Sigils
    • Elixir Comprehensions
    • Elixir Typespecs
    • Elixir Behaviours
    • Elixir Errors Handling
    • Elixir Macros
    • Elixir Libraries
  • TypeScript
    • TypeScript Overview
    • Install TypeScript
    • First TypeScript Program
    • Type Annotation
    • TypeScript Variable
    • TypeScript Data Type Number
    • TypeScript Data Type String
    • TypeScript Data Type Boolean
    • TypeScript Arrays
    • TypeScript Tuples
    • TypeScript Enum
    • TypeScript Union
    • TypeScript Any Data Type
    • TypeScript Void Data Type
    • TypeScript Never Data Type
  • Home
  • PHP Introduction
  • PHP Install
  • PHP Syntax
  • PHP Comments
  • PHP Variables
  • PHP Echo / Print
  • PHP Data Types
  • PHP Strings
  • PHP Constants
  • PHP Operators
  • PHP If...Else...Elseif
  • PHP Switch
  • PHP Loops
  • PHP Functions
  • PHP Arrays
  • PHP Superglobals
  • PHP Date and Time
  • PHP Include
  • PHP File Handling
  • PHP File Upload
  • PHP Cookies
  • PHP Sessions
  • PHP Filters
  • PHP Callback Functions
  • PHP JSON
  • PHP Exceptions
  • PHP What is OOP
  • PHP Classes/Objects
  • PHP Constructor
  • PHP Destructor
  • PHP Access Modifiers
  • PHP Inheritance
  • PHP Abstract Classes
  • PHP Interfaces
  • PHP Traits
  • PHP Static Methods
  • PHP Namespaces
Home >> php >> PHP Arrays

PHP Arrays

This tutorial on PHP Arrays helps you learn what an array is and how you can create arrays. So, let us start.

 

What is a PHP Array?

An array stores multiple values, generally of the same type, in a single variable.

For example, in case you have a list of festivals that you want to store together, or maybe a list of stationery items, or a list of colors. In that case, you have an option to keep them in separate variables, but in this case, you will have to create a lot of variables, and they won't be related to each other.

In such a case, PHP arrays are used. This is because arrays can be used to store multiple values together in a single variable. You can use the foreach loop to traverse all the values stored in the array.

 

Creating an Array

An array can be created in PHP using the array() function.

Syntax:

<?php 

/* this function takes multiple values 

separated by comma as input to create an aray */ 

array(); 

?>

 

There are three types of arrays in PHP:

  • Indexed Array: These are arrays with a numeric index.
  • Associative Array: These arrays have a named key as index; the key can be numeric or text.
  • Multidimensional Array: These are arrays that contain one or more arrays.

 

Example:

<?php
/* 
    a simple array with car names
*/
$lamborghinis = array("Urus", "Huracan", "Aventador");

?>

 

You can access the data stored in an array by either using the index numbers or using a foreach loop for traversing the array elements.

The index number for array elements starts from 0, i.e., the first element is at position 0, then the next element at position 1, the third element at position 3, and so on…

<?php
/* 
    a simple array with Lamborghini car names
*/
$lamborghinis = array("Urus", "Huracan", "Aventador");
// print the first car name
echo $lamborghinis[0];
echo "Urus is the latest Super SUV by Lamborghini";

?>

Output:

Urus
Urus is the latest Super SUV by Lamborghini

 

Advantages of Array

Some of the advantages of using an array in our program/script:

  • It's very easy to define a simple list of related data instead of creating multiple variables.
  • Arrays are easy to use and can be traversed using the foreach loop.
  • PHP provides built-in functions for sorting arrays; hence, you can use arrays to sort information.

 

PHP Indexed Arrays

You can store the data elements in an indexed array against numeric indexes. An index represents all the array elements. The index is a numeric value that starts from 0 for the first array element.

 

Creating an Indexed Array

You can create an indexed array in PHP in two different ways. These are,

The syntax for the first way to create an indexed array:

<?php 

/* 1st - direct array initialization */ 

$lamborghinis = array("Urus", "Huracan", "Aventador"); 

?>

The syntax for the second way to create an indexed array:

<?php 

/* 2nd - distributed array initialization */ 

$suzuki[0] = "Swift"; 

$suzuki[1] = "Baleno"; 

$suzuki[2] = "Ertiga"; 

$suzuki[3] = "Brezza"; 

$suzuki[4] = "Vitara"; 

?>

 

Regardless of how much we initialize the array, the array can be accessed only as follows,

<?php
/* 
    Accessing array
*/
echo "Accessing the 2nd array...";
echo $suzuki[0], "n";
echo $suzuki[3], "n";
echo $suzuki[2], "n";

echo "Accessing the 1st array...";
echo $lamborghinis[1], "n";
echo $lamborghinis[0], "n";
echo $lamborghinis[2], "n";

?>

Output:

Accessing the 2nd array...
Swift
Brezza
Ertiga
Accessing the 1st array...
Huracan
Urus
Aventador

Therefore, for accessing an indexed array, we have to use the name of the array along with the element's index in square brackets.

 

Traversing PHP Indexed Array

Traversing an array means iterating it starting from the first index to the array's last element.

An indexed array can be traversed by either using a for loop or foreach. You can refer to the tutorials on PHP for and foreach loop to know their syntax and basic usage.

 

Using for loop

If you are using the for loop for traversing an indexed array, then you must know the size/length of the array. You can find it by using the count() function.

The syntax to traverse an array using the for loop is as follows.

<?php

$lamborghinis = array("Urus", "Huracan", "Aventador");
// find size of the array
$size = count($lamborghinis);

// using the for loop
for($i = 0; $i < $size; $i++)
{
    echo $lamborghinis[$i], "n";
}

?>

 

Using the foreach loop

It is better to use foreach to traverse an indexed array in case you want to traverse the whole array. The reason is it does not require you to be bothered about calculating the array's size to loop around the array.

Here we have used the foreach for traversing the $lamborghinis array.

<?php

$lamborghinis = array("Urus", "Huracan", "Aventador");

// using the foreach loop
foreach($lamborghinis as $lambo)
{
    echo $lambo. "n";
}

?>

 

Advantages of Indexed Array- 

It is easier to use because of the numeric index values. Having numeric indexes is common to almost all programming languages; it makes the code more readable for others who go through your code.

 

 

PHP Associative Arrays

It is similar to an indexed array. However, you can assign every value with a user-designed string type key rather than storing data sequentially with a numeric index.

 

Creating an Associative Array

You can create an associative array in two different ways; these are,

Syntax for the first way to create associative array:

<?php 

/* 1st - direct array initialization */ 

$lamborghinis = array("suv"=>"Urus", "sports"=>"Huracan", "coupe"=>"Aventador"); 

?>

 

and the syntax for the second way to create associative array is:

<?php 

/* 2nd - distributed array initialization */ 

$suzuki["hatch"] = "Swift"; 

$suzuki["utility"] = "Ertiga"; 

$suzuki["suv"] = "Vitara"; 

?>

 

Regardless of how much we initialize the array, we can access the array as follows,

<?php
/* 
    Accessing array
*/
echo "Accessing the 2nd array...";
echo $suzuki["hatch"], "n";
echo $suzuki["utility"], "n";
echo $suzuki["suv"], "n";

echo "Accessing the 1st array...";
echo $lamborghinis["suv"], "n";
echo $lamborghinis["sports"], "n";
echo $lamborghinis["coupe"], "n";

?>

Output:

Accessing the 2nd array...
Swift
Ertiga
Vitara
Accessing the 1st array...
Urus
Huracan
Aventador

 

Traversing PHP Associative Array

Traversing an array means iterating it starting from the first index to the array's last element.

An associative array can be traversed either by using a for loop or foreach. You can check the PHP for and foreach loop tutorial for learning their syntax and basic usage.

 

Using for loop

To traverse an associative array when you are using the for loop, you must know the array's size/length, which you can find using the count() function.

Also, as the index in an associative array is neither numeric nor sequential, therefore for finding the index values or keys (because the data saved in the associative array is in the key-value form), the array_keys() function can be used for getting an array of the keys that are used in the associative array.

The syntax to traverse an array using the for loop is as follows.

<?php

$lamborghinis = array("Urus", "Huracan", "Aventador");

// find size of the array
$size = count($lamborghinis);

// getting the array of keys/index strings
$keys = array_keys($lamborghinis);

// using the for loop
for($i = 0; $i < $size; $i++)
{
    echo $lamborghinis[$keys[$i]] ." is a/an ". $keys[$i] ." car n";
}

?>

Output:

Urus is a/an suv car
Huracan is a/an sports car
Aventador is a/an coupe car

 

Using the foreach loop

It is better to use foreach for traversing an associative array in case you want to traverse the whole array. Then, you are not required to bother about calculating the array's size to loop around the array.

Here the foreach loop has been used for traversing the $lamborghinis array.

<?php

$lamborghinis = array("Urus", "Huracan", "Aventador");

// using the foreach loop
foreach($lamborghinis as $key => $value)
{
    echo $value ."is a/an ". $key ." car n";
}

?>

Output:

Urus is a/an suv car
Huracan is a/an sports car
Aventador is a/an coupe car

 

The syntax is $key=>$value means in every iteration of the foreach, the array as key-value pair is represented.

 

Advantages of Associative Array

Here are a few advantages of using an associative array in our program/script:

  • A more meaningful key or index value can be provided to our array elements.
  • More data can be saved, as we can have a string as a key to the array element, where we can associate data to the value that has to be stored, just as in our example, we stored the type of the car as a key along with the car name as value. Thereby storing two different information in one array element.

 

PHP Multidimensional Arrays

A multidimensional array is an array that stores another array at each index instead of storing a single value. It is an array of arrays.

Generally, you can store associative arrays inside multidimensional arrays.

 

Creating a Multidimensional Array

Since it is an array of arrays, therefore it holds the associative arrays inside it.

 

Syntax for creating multidimensional array:

<?php 

/* multidimensional array initialization */ 

$cars = array( 

array( 

"name"=>"Urus", 

"type"=>"SUV", 

"brand"=>"Lamborghini"

 ),

 array( 

"name"=>"Cayenne", 

"type"=>"SUV", 

"brand"=>"Porsche" 

), 

array( 

"name"=>"Bentayga",

 "type"=>"SUV", 

"brand"=>"Bentley" )

, ); 

?>

 

Since an array inside an array is being dealt with here, to access any information, we first need to reach that array and, after that, get data from the particular array stored in the multidimensional array.

For instance, in case you want to display data for the Urus car, then first, you will have to get the first array inside your multidimensional array, which can be accessed using index 0. Then inside that array, you can display all the data, as was done in associative arrays.

 

<?php
/* 
    Accessing multidimensional array
*/
echo "Accessing multidimensional array...";
echo "Urus is an ".$cars[0]["type"]." manufactured by ".$cars[0]["brand"]."n";
echo "Bentayga is an ".$cars[2]["type"]." manufactured by ".$cars[2]["brand"]."n";

?>

Output:

Accessing multidimensional array...
Urus is an SUV manufactured by Lamborghini
Bentayga is an SUV manufactured by Bentley

 

Traversing PHP Multidimensional Array

Traversing an array means iterating it starting from the first index to the array's last element.

A multidimensional array can be traversed either by using two for loops or by using two foreach loops or one for loop and one foreach. You can check the PHP for and foreach loop tutorial to know their syntax and basic usage.
 

Using one for loop and one foreach

In a multidimensional array, you are required to traverse the main array and then traverse the arrays that are stored inside the main arrays; hence you need two loops.

If you are using the for loop for traversing a multidimensional array, then you should know the array's size/length, which you can find utilizing the count() function.

Let us consider the array defined above for the first example of traversing a multidimensional array.

<?php
/* 
    multidimensional array initialization
*/
$cars = array(
    array(
        "name"=>"Urus", 
        "type"=>"SUV", 
        "brand"=>"Lamborghini"
    ),
    array(
        "name"=>"Cayenne", 
        "type"=>"SUV", 
        "brand"=>"Porsche"
    ),
    array(
        "name"=>"Bentayga", 
        "type"=>"SUV", 
        "brand"=>"Bentley"
    ),
);

// array traversal
// find size of the array
$size = count($lamborghinis);

// using the for loop
for($i = 0; $i < $size; $i++)
{
    foreach($cars[$i] as $key => $value) {
        echo $key . " : " . $value . "n";
    }
    echo "n";
}

?>

Output:

name : Urus
type : SUV
brand : Lamborghini

name : Cayenne
type : SUV
brand : Prosche

name : Bentayga
type : SUV
brand : Bentley

 

In the multidimensional array above, the main array is an indexed array, and the arrays stored as elements are associative.

However, the main array can also be associative; let us take an example for it.

Also, as the index in an associative array is neither numeric nor sequential, therefore for finding the index values or keys(because the data saved in the associative array is in the key-value form), the function array_keys() can be used to get an array of the keys used in the associative array.

<?php
/* 
    multidimensional array initialization
*/
$cars = array(
    "Urus" => array(
            "type"=>"SUV", 
            "brand"=>"Lamborghini"
        ),
    "Cayenne" => array(
            "type"=>"SUV", 
            "brand"=>"Porsche"
        ),
    "Bentayga" => array(
            "type"=>"SUV", 
            "brand"=>"Bentley"
        ),
);

/* 
    array traversal
*/
// find size of the array
$size = count($lamborghinis);

// array keys
$keys = arra_keys($cars);

// using the for loop
for($i = 0; $i < $size; $i++)
{
    echo $keys[$i]. "n";
    foreach($cars[$keys[$i]] as $key => $value) {
        echo $key . " : " . $value . "n";
    }
    echo "n";
}

?>

Output:

Urus
type : SUV
brand : Lamborghini

Cayenne
type : SUV
brand : Prosche

Bentayga
type : SUV
brand : Bentley

 

Advantages of Multidimensional Array

Some advantages of using a multidimensional array in our program/script:

  • It can store detailed information in a multidimensional array.
  • On the top level, you can either keep it indexed or associative, thereby making it more user-friendly, as it can be used as per their requirements.

 

  • Prev
  • Next


-Advertisement-


DeveloperTutorial
[email protected] © 2022-2023 Developers Tutorial All rights reserved.

Follow Us

Facebook Twitter LinkedIn Printerest Reddit

Announcement

Its a big achivement for us, We make a partnership with TutorialWithExample.com for the better content of our users.

Still Need Help ?

Let us now about your issue and a Professional will reach you out.