Arrays in PHP
Let us suppose that we need 10 variables of similar data types to store ten web addresses. We can use ten variables to store the information. Managing 10 variables will be difficult. PHP provides Array to store similar values. Many a times arrays are used to get a ramdom number out of fixed set of numbers. The syntax to declare an array in PHP is as given below.
$arr = array("1","2","3");
Alternatively we can create a new similar array with same values as below.
$arr[0] = "1";
$arr[1] = "2";
$arr[2] = "3";
To access any of the array element, we refer its position. The position begins with 0 (zero). For example the following code will output 3. You may or may not create an empty array in php. In the example above, first array element is created on the first statement then other elements are appended to the array.
echo $arr[2];
Apart from the above type of arrays where we refer an array element by its position, PHP has another type of array, the associative array. We will learn about associative arrays in the next section.
Unlike the numeric type of arrays discussed in the previous section, the elements of an associative array is accessed using a key name also. This key name is assigned to a position while creating the array. The example of creating an associative array is as given below.
$person = array(
"name"=>"John",
"age"=>"23",
"address"=>"36,Chinatown"
);
Now We can access each element of the above array by its key or by its position as described below.
//By key
echo "Name is ".$person["name"]."<br>";
echo "Age is ".$person["age"]."<br>";
echo "Address is ". $person["address"]."<br>";
The output of the above code is given below.
Name is John
Age is 23
Address is 36,Chinatown
unset($arr[0]);
To unset an associative array element we will use the following syntax.
unset($arr["first_element"]);
If we access an array element which we have unset, the null value is returned.
If we want to empty a whole array (all elements of the array are unset at a time), we can use the following code.
unset($arr);
- 542 reads
