"I am Saqib Jahangir. A passionate vlogger, software engineer, trainer and avid traveler with a deep love for exploring the hidden gems of our beautiful planet. With a strong foundation in Application Development, Application Architecture & Database Design and Product Management, I bring over a decade of hands-on experience building secure, scalable, and resilient web applications for a diverse range of industries."

Arrays (Indexed, Associative, Multidimensional)

 

Introduction

An array in PHP is a data structure that stores multiple values in a single variable. Arrays make it easy to work with lists of data without creating separate variables for each item. PHP supports three main types of arrays: Indexed, Associative, and Multidimensional.


Indexed Arrays

Indexed arrays store values with numeric indexes starting from 0. They are useful when you only need to access values by their position.

Example:


<?php $colors = ["Red", "Green", "Blue"]; echo $colors[0]; // Outputs: Red echo $colors[1]; // Outputs: Green echo $colors[2]; // Outputs: Blue ?>

Associative Arrays

Associative arrays use named keys instead of numeric indexes. They are helpful when you want to access elements by a meaningful name rather than a number.

Example:


<?php $person = [ "name" => "John", "age" => 30, "city" => "Dubai" ]; echo $person["name"]; // Outputs: John echo $person["city"]; // Outputs: Dubai ?>

Multidimensional Arrays

Multidimensional arrays are arrays that contain other arrays. They are useful for representing complex data structures, such as tables or nested information.

Example:


<?php $students = [ ["John", 20, "A"], ["Sara", 22, "B"], ["Mike", 19, "A+"] ]; echo $students[0][0]; // Outputs: John echo $students[1][2]; // Outputs: B ?>

Using print_r to Display Arrays

The print_r() function is useful for quickly displaying the structure and contents of an array, especially while debugging.

Example:


<?php $fruits = ["Apple", "Banana", "Cherry"]; print_r($fruits); ?>

Output:


Array ( [0] => Apple [1] => Banana [2] => Cherry )

Looping Through Arrays

You can use the foreach loop to iterate through arrays easily.

Example:


<?php $fruits = ["Apple", "Banana", "Cherry"]; foreach ($fruits as $fruit) { echo $fruit . "\n"; } ?>

Output:


Apple Banana Cherry

Popular Posts

Operators (Arithmetic, Comparison, Logical)

Functions (Built-in & User-defined)