PHP Indexed Arrays

0 0
Read Time:44 Second

PHP Indexed Arrays

Syntax:

Syntax for indexed arrays:

array(value1, value2, value3, .....)

There are two ways to create indexed arrays:

The index can be assigned automatically (index always starts at 0), like this:

$names= array("Gaurav Dixit", "Sagar", "Vaibhav");

or the index can be assigned manually:

$names[0] = "Gaurav Dixit";
$names[1] = "Sagar";
$names[2] = "Vaibhav";

The following example creates an indexed array named $names, assigns three elements to it, and then prints a text containing the array values:

<?php
$names = array("Gaurav Dixit", "Sagar", "Vaibhav");
echo "I like ". $names[0].", ".$names[1]." and ".$names[2].".";
?>

Loop Through an Indexed Array

To loop through and print all the values of an indexed array, you could use a for loop, like this:

<?php
$names = array("Gaurav Dixit", "Sagar", "Vaibhav");
$arrlength = count($names);

for($x = 0; $x < $arrlength; $x++) {
  echo $names[$x];
  echo "<br>";
}
?>
Happy
Happy
0 %
Sad
Sad
0 %
Excited
Excited
0 %
Sleepy
Sleepy
0 %
Angry
Angry
0 %
Surprise
Surprise
0 %

Average Rating

5 Star
0%
4 Star
0%
3 Star
0%
2 Star
0%
1 Star
0%

Leave a Comment

Verified by MonsterInsights