Arrays in PHP

Getting Started with PHP
Getting Started with PHP : Home
Introduction
Installation
Hello World
Data Types in PHP
Variables in PHP
Operators in PHP
Decision Making in PHP
Iterations in PHP
Functions in PHP
Arrays in PHP
Strings in PHP
Object Oriented PHP
Classes and Objects
Constructors
Inheritance
Object Interfaces
Static and Final
Advanced Features in PHP
GET and POST
Session in PHP
Cookies in PHP
Server Variables

Array
An array is a collection of elements of similar types like you can array of integers that contains many integers. Creating in array is very simple in PHP. You can create array using array(args) function and simply passing values seprated by , as args.
A single element of an array can be accessed using $array_name[key]. You might be wondering what is a key?

Key : In an array each value is mapped with a key i.e. each value you store in an array is given a key to access that particular value.
The default keys are intergers (0 for the 1st value and 1 for second value and so on).
You can have customized keys as well by givng args as key=>value seprated by ,.

<?php
// An array without customized keys
$normal_array = array(1,1,2,3,4);
// Array with customized keys
// Here "Jon" and "Sam" are keys and "27 North Avenue" Value
$array_with_key = array("Jon"=>"27 North Avenue", "Sam"=>"Somewhere on earth");

// Accesing 3rd element of noemal array
echo $normal_array[2]."<br>";

// Accessing value associated with key "Sam"
echo $array_with_key["Sam"];
?>


Output
2
Somewhere on earth

foreach
PHP provides foreach loop specially designed for handling array. Here if you need to run a loop for every element of an array you don't need to know the total elements of array or all the keys. This loop will ensure to run through every elements that the array holds.

Syntax : foreach($array_name as $value) and you can value of that element in the loop using $value.
If you also need keys inside loop you can use alternate syntax :
foreach($array_name as $key=>$value) and key can be accessed using $key inside loop.

<?php

$normal_array = array(1,1,2,3,4);
// Lets increment every value of array by 1

foreach ($normal_array as $key=>$value) {
    $normal_array[$key] = $value+1;

// Keep in mind that any changes made to $value will not afftect
// the array.
    }
// accessing new values
    echo $normal_array[0]."<br>".$normal_array[2]."<br>";
    echo $normal_array[3];

?>


Output
2
3
4

Login to Track Your Progress