Saturday, 15 December 2012

Arrays in PHP

Arrays in PHP

In this tutorial we will explain you how to work with arrays in php. You will learn how to create, sort or print an array. Besides this we will touch on multidimensional arrays as well.

Arrays are special data types. Despite of other normal variables an array can store more than one value. Let's suppose you want to store basic colors in your PHP script. You can construct a small list from them like this:

Color list:
* red
* green
* blue
* white

It is quite hard, boring, and bad idea to store each color in a separate variable. It would be very nice to have the above representation almost as it is in PHP. And here comes array into play.

The array type exists exactly for such purposes. So let's see how to create an array to store our color list. There are more ways to create an array in PHP. Maybe the most easiest way to create our color list array is the following:

$color_array[0] = "red";
$color_array[1] = "green";
$color_array[2] = "blue";
$color_array[3] = "white";
or
$color_array = array("red","green","blue","white",);

Numerically Indexed Array

Numerically Indexed Array is nothing but the array elements identified by the numeric value.like this below example

$color_array[0] = "red";
$color_array[1] = "green";
$color_array[2] = "blue";
$color_array[3] = "white";

Associative Arrays

Associative Array is nothing but the array elements identifieds by their element associative string. Look at the below example:

$basevalues["binary"] = 2;
$basevalues["octal"] = 8;
$basevalues["decimal"] = 10;
$basevalues["hexa_decimal"] = 16;
echo "Base value of binary - " . $basevalues["binary"] . "<br />";
echo "Base value of octal - " . $basevalues["octal"] . "<br />";
echo "Base value of decimal - " . $basevalues["decimal"] . "<br />";
echo "Base value of hexa decimal - " . $basevalues["hexa_decimal"];

output of above program
Base value of binary - 2
Base value of octal - 8
Base value of decimal - 10
Base value of hexa decimal - 16

0 comments:

Post a Comment