Php Arrays Tutorial
PHP array is an ordered collection of data. PHP Arrays are very easy to create. PHP Arrays are dynamic - Items can be added and removed at will.
PHP Arrays can be created in two different ways
- Using array() construct
- Using array Operator []
PHP Arrays using Array Operator []
Array operator [] can be used to create an array in PHP. A general syntaxt of array operator for the creation of an array in PHP is
$array_neme['key'] = array_value;
Here we are going to discuss two main types of PHP arrays using array operator - Numeric Arrays & Associative Arrays
PHP Numeric Arrays
<?
$ar[0] = "Noni";
$ar[1] = "Shahid";
$ar[2] = "Madrassi";
echo $ar[0];
echo $ar[1];
echo $ar[2];
echo "<BR>";
?>
PHP Associative Arrays
<?
$score['Noni'] = "32";
$score['shahid'] = "30";
$score['madrassi'] = "35";
echo $score['Noni'];
echo "<BR>";
echo $score['shahid'];
echo "<BR>";
echo $score['madrassi'];
echo "<BR>";
?>
PHP Arrays using array() Construct
PHP uses array() construct to create an array. The structure of creation of array using array() construct is really simple, simply type array() and it will create an array. A general syntax for array() would be
array(key => value, key => value, key => value)
some examples of php array() constructs are given here
<?php
array();
array(1, 222, 33, 55);
array('price', 'category', 'quantity');
array(3 => 1, 4 => 453);
array('a' => 2, 'b' => '33');
array('a' => 'first data', 'b' => 'second');
?>
// Creating a simple array of numbers $myArray = array(1, 3, 4, 5);
// Creating a simple array of strings $myArray2 = array('cats', 'dogs', 'chickens');
// Arrays can contain items of different types, and even other nested arrays $myMixedArray = array('monkeys', 5, 3.7, array('a nested array', 'blah'), 'something');
// Array elements are accessed by their index, counting from 0 echo $myArray2[0]; // Outputs "cats" echo $myArray2[2]; // Outputs "chickens"
// Cycling through an array can be achieved using a for loop... for ($i = 0; $i < count($myArray); $i++) { echo $myArray[$i]; }
// ... or using the special foreach language construct foreach ($myArray as $item) { echo $item; }
// Creating an indexed array (aka a hash table) is easy: $indexedArray = array( 'firstname' => 'Simon', 'lastname' => 'Willison', 'age' => 21 );
// Items in an indexed array can be accessed by key: echo $indexedArray[‘firstname’]; // outputs “Simon” // Adding items to the end of an array can be done with: $myArray[] = ‘something’; // Items in an array can be replaced by assignign to their index $myArray[2] = ‘blah’;
An invaluable function for debugging an array is print_r() , which prints out any PHP data structure (no matter how complex or nested) in a nice human readable format. Try the following and see what happens:
print_r($_SERVER); // Prints out the array of server variable print_r($GLOBALS); // Prints out the array of every assigned variable in your PHP script!

