PHP Array


 

PHP Array

PHP Array Example. You will learn the concept of PHP Array.

PHP Array Example. You will learn the concept of PHP Array.

The meaning of an array is almost same in all programming language but there could be different ways to define it. In simple words an array is used to logically store and sequence data. Basically it is a list of certain variables and these variables in the list can be referenced by unique index numbers starting at 0.[...] or associative. In PHP programming arrays are generally used for either to count the elements of an array or iterate through key-value pairs but in actual an array can do more then that.

An array take it's parameters separated by commas. i.e. 

Syntax of defining array () in PHP

$arrayname = array ( "key"  => "value", "key1"  => "value1",...) and so on... A key can be either Integer or String type.

You can define array in both the ways... 

Method 1. 
$myArray[] = "Hi there!";

or 

Method 2.
 $numbers[0] = 49;

In method one you can see that we have not defined any key value to it. In such cases integer key is generated starting at 0 and increased by one for each value.

In this series of PHP tutorial we have talked about array, now lets take a small example to see how it actually works.

 PHP Example: Creating an array in PHP

Fist of all lets see how to define an array..

Defining an array in php

<?PHP

$colors = array ();

?>

In the above given code, we have initialize the array but there is no value defined in it or in other words the array is blank.  We can assign some value to it and show it on the screen, look at the example to see how this work.

<?PHP

$colors = array( "Red", "Green", "Yellow", "Blue");

foreach ($colors as &$value) {
echo $value."<br>";
}

echo $colors;
?>

Output of creating an array in PHP example

Red
Green
Yellow
Blue
Array

 

Ads