Mastering PHP Arrays – A Comprehensive Guide

Arrays PHP Techhyme

Arrays in PHP are versatile data structures that allow you to store and manage multiple values within a single variable.

In this guide, we’ll explore three types of arrays: Indexed arrays, Associative arrays, and Multi-dimensional arrays, providing examples to demonstrate their usage.

1. Indexed Arrays

Indexed arrays use numeric indices to access their elements, with indexing starting from 0. They are declared using the `array()` function.

Syntax

$directions = array("East", "West", "North", "South");

Example

<?php
  $directions = array("East", "West", "North", "South");
  $length = count($directions);

  for($i=0; $i < $length; $i++) {
    echo "$directions[$i]\n";
  }
?>

 

Output:

East
West
North
South

2. Associative Arrays

Associative arrays use key-value pairs, allowing you to access elements using keys. They are declared using the `array()` function with explicit key-value assignments.

Syntax

$capitals = array(
  "Japan" => "Tokyo",
  "India" => "New Delhi",
  "United Kingdom" => "London",
  "United States" => "Washington, D.C.",
  "China" => "Beijing"
);

Example

<?php
  $capitals = array(
    "Japan" => "Tokyo",
    "India" => "New Delhi",
    "United Kingdom" => "London",
    "United States" => "Washington, D.C.",
    "China" => "Beijing"
  );
  foreach($capitals as $key => $value) {
    echo "Capital of ". $key . " is " . $value. "\n";
  }
?>

Output:

Capital of Japan is Tokyo
Capital of India is New Delhi
Capital of United Kingdom is London
Capital of United States is Washington, D.C.
Capital of China is Beijing

3. Multi-dimensional Arrays

Multi-dimensional arrays can store other arrays, creating a structured hierarchy. A common example is the two-dimensional array.

Syntax

$num = array(
array(1,2,3),
array(4,5,6),
array(7,8,9)
);

Example

<?php
  $num = array(
    array(1,2,3),
    array(4,5,6),
    array(7,8,9)
  );

  for ($i = 0; $i < 3; $i++){
    for ($j=0; $j <3; $j++){
      echo($num[$i][$j]);
      echo("\t");
    }
    echo("\n");
  }
?>

Output:

1   2   3
4   5   6
7   8   9

Mastering these array types empowers you to efficiently organize and manipulate data in PHP. Arrays are fundamental in programming, providing the flexibility to handle complex datasets and build dynamic applications.

You may also like:

Related Posts

Leave a Reply