Learn How To Use Indexed Array With Example In PHP

admin_img Posted By Bajarangi soft , Posted On 24-09-2020

The index can be assigned automatically index always starts at 0

PHP Indexed Arrays with example

First Need to Create  Indexed Arrays

Create Indexed Arrays:
There are two ways to create indexed arrays:


1.Indexed Arrays can be assigned automatically (index  starts at 0).

$Fruits = array("Cherries", "Mango", "Grape","Blueberry");

2.Indexed Arrays can be assigned manually(index  starts at 0).
 
$Fruits [0] = "Cherries";
$Fruits [1] = "Mango";
$Fruits [2] = "Grape";
$Fruits [3] = "Blueberry";

Example(1)
 
<?php

$Fruits=array("Cherries","Mango","Grape","Blueberry");
echo "I like ".$Fruits[0].",".$Fruits[1].",".$Fruits[2]." and ".$Fruits[3].".";

?>

We Can also Use Loop For an Indexed Arrays:
Print all the values of an indexed arrays through the for loop


Example(2)
 
<?php

$Fruits=array("Cherries","Mango","Grape","Blueberry");
$arraylength = count($Fruits);

for($i = 0; $i < $arraylength; $i++) {
    echo $Fruits[$i];
    echo "<br>";
}

?>


Complete Code of An Index Array:
<!DOCTYPE html>
<html lang="en">
<head>
<title>PHP Indexed Arrays</title>
       
    <meta charset="utf-8">
       
    <meta name="viewport" content="width=device-width, initial-scale=1">
       
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
       
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
       
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
       
    <div class="text-center">
        <h1>PHP Index arrays</h1>
    </div>
    <br>
    <h2>1.Creating Index Arrays Without Loop</h2>
    <div class="well">
        <?php
        $Fruits = array("Cherries", "Mango", "Grape", "Blueberry");
        echo "<h3> I like " . $Fruits[0] . "," . $Fruits[1] . "," . $Fruits[2] . " and " . $Fruits[3] . ".</h3>";
        ?>
    </div>
    <h2>2.Creating Index Arrays With Loop</h2>
    <div class="well">
                <?php
        $Fruits = array("Cherries", "Mango", "Grape", "Blueberry");
        $arrlength = count($Fruits);
        for ($i = 0; $i < $arrlength; $i++)
        {
            echo "<h1>" . $Fruits[$i] . "</h1>";
        }
        ?>
    </div>
</div>
</body>
</html>

 


 

Related Post