PHP Arrays

PHP Array is usedto hold more than one value at a time.  In another words, we can say that an array stores multiple values in one single variable. Following are the advantages of Array.

  • It reduces the code.
  • We can store data easily.
  • Easy to traverse.
How to create Array in PHP In PHP, the array() function is used to create an array. Syntax:
array();
Example
<?php
$arr = array(10,11,12,13,14,15);                    
echo $arr[0];                      
?>
Output 10 There are three types of array in PHP:
  1. Indexed Array
  2. Associative Array
  3. Multidimensional Array
PHP Indexed Arrays PHP indexed array is used to store the number, string and object. Itis represented by number andstarts with 0. There are two ways to represent indexed array: 1stway:
$name=array("Rohit","Rohan","Shyam");
Example 1:
<!DOCTYPE html>
<html>
<head>
<title>PHP Tutorial</title>
</head>
<body>
            <?php
            $name=array("Geeta","Rohan","Shyam");
echo "Your Name: $name[0],$name[1],$name[2]";
?>
</body>
</html>
Output Your Name: Geeta,Rohan,Shyam 2nd Ways:
$name[0]="Geeta";
            $name[1]="Rohit";
            $name[2]="Shyam";
Example2
<!DOCTYPE html>
<html>
<head>
<title>PHP Tutorial</title>
</head>
<body>
            <?php
            $name[0]="Geeta";
            $name[1]="Rohit";
            $name[2]="Shyam";
echo "Your Name: $name[0],$name[1],$name[2]";
            ?>
</body>
</html>
Output Your Name: Geeta,Rohit,Shyam Exqmple3
<html>
<head>
<title>PHP Tutorial</title>
</head>
<body>
<?php
            $size=array("Geeta","Rohit","Shyam");
//Traversing PHP Indexed Array
            foreach($size as $s){
            echo "Your Name:$s<br />";
            }
?>
</body>
</html>
Output Hello John Hello Ram Hello Rohan Example4
<!DOCTYPE html>
<html>
<head>
<title>PHP Tutorial</title>
</head>
<body>
<?php
$size=array("Geeta","Rohit","Shyam");
echo count($size);
?>
</body>
</html>
Output 3



ADVERTISEMENT
ADVERTISEMENT