Wednesday 7 September 2011

PHP Tutorial Ch-03 Arrays in PHP



CHAPTER-3 Arrays in PHP
Arrays in PHP can be declared using any of the following ways-
  • $arrayVar=array(‘string1’, ’string2’, ’string3’);
This is a simple array declaration where we pass the array elements to the array function’s parameters. The keys of an array declared like this would start from 0. You can access the array elements as-
$arrayVar[0];
$arrayVar[1];
$arrayVar[2];

  • $arrayVar[0]=’string1’;  $arrayVar[1]=’string2’;  $arrayVar[2]=’string3’;
In this array declaration we assign the array keys manually. The indexes maybe of any primitive datatype. That is we can even have string values as the array indexes. For example-
$arrayVar[‘FirstName’]=”userName”;
$arrayVar[‘LastName’]=”lastUserName”;
is absolutely valid in PHP.

  • $arrayVar=array(‘FirstName’=>’userName’, ‘LastName’=>’lastUserName’);
The above array declaration is associative. In the array function we provide both the array key and array element. The general syntax is-
array(keyname=>element, keyname=>element, ……..);
An array declared like this will be used just like in the previous example. In fact, this example and the previous example do the same thing. In both the examples the array elements will be accessed as-
$arrayVar[‘FirstName’];
$arrayVar[‘LastName’];

Here’s an example that demonstrates all of the array declaration methods-
<?php
$name=array("Jitin","Saurabh","Saurav");
$mark=array(502,486,423);
echo $name[0]."-".$mark[0]."<br>";
echo $name[1]."-".$mark[1]."<br>";
echo $name[2]."-".$mark[2]."<br><br>";
 

$marks['Jitin']=502;
$marks['Saurabh']=486;
$marks['Saurav']=423;
echo $marks['Jitin']."<br>";
echo $marks['Saurabh']."<br>";
echo $marks['Saurav']."<br><br>";
 

$marksOf=array('Jitin'=>502, 'Saurabh'=>486, 'Saurav'=>423);
echo $marksOf['Jitin']."<br>";
echo $marksOf['Saurabh']."<br>";
echo $marksOf['Saurav']."<br><br>";
?>

OUTPUT:
Jitin-502
Saurabh-486
Saurav-423
502
486
423
502
486
423

In the above example we declare 4 arrays namely- $name and $mark, $marks, $markOf.
The arrays $name and $mark have been declared using the first method. So in the subsequent echo statements the array elements are accessed by using array keys starting from 0.

The array $marks is declared using the second method. The key names are assigned manually. So the elements of this array is referred using the key names ‘Jitin’, ‘Saurabh’ and ‘Saurav’.

The fourth array $markOf is declared using the third method. Here the key names are provided in the array functions parameters itself. This method is basically a shorter and better method for the previous method.

So now that we know about declaring arrays in PHP, let’s move on to the next chapter.

No comments:

Post a Comment