HOME C C++ PYTHON JAVA HTML CSS JAVASCRIPT BOOTSTRAP JQUERY REACT PHP SQL AJAX JSON DATA SCIENCE AI

PHP Indexed Arrays

PHP Indexed Arrays are a fundamental data structure used to store and manage an ordered collection of elements. Each element is assigned a unique numeric index (starting from 0).


Example

Create and display an indexed array:


<!DOCTYPE html>
<html>
<body>
<pre>

<?php
$cars = array("Volvo", "BMW", "Toyota"); 
var_dump($cars);
?>

</pre>
</body>
</html>

Output

array(3) {
[0]=>
string(5) "Volvo"
[1]=>
string(3) "BMW"
[2]=>
string(6) "Toyota"
}

• Access Indexed Arrays

To access an array item you can refer to the index number.

  • An indexed array is a fundamental data structure in PHP that stores a collection of values using numerical indexes as keys.
  • The first element has an index of 0, the second has an index of 1, and .
  • These indexes are integers starting from 0.

  • Example

    Display the first array item:


    <!DOCTYPE html>
    <html>
    <body>
    
    <?php
    $cars = array("Volvo", "BMW", "Toyota"); 
    echo $cars[0];
    ?>
    
    </body>
    </html>
    
    

    Output

    Volvo

    • Change Value

    To change the value of an array item, use the index number:


    Example

    Change the value of the second item:


    <!DOCTYPE html>
    <html>
    <body>
    <pre>
    
    <?php
    $cars = array("Volvo", "BMW", "Toyota"); 
    $cars[1] = "Ford";
    var_dump($cars);
    ?>
    
    </pre>
    </body>
    </html>
    
    
    

    Output

    array(3) {
    [0]=>
    string(5) "Volvo"
    [1]=>
    string(4) "Ford"
    [2]=>
    string(6) "Toyota"
    }


    • Loop Through an Indexed Array

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


    Example


    Display all array items:

    <!DOCTYPE html>
    <html>
    <body>
    
    <?php
    $cars = array("Volvo", "BMW", "Toyota"); 
    
    foreach ($cars as $x) {
      echo "$x 
    "; } ?> </body> </html>

    Output

    Volvo
    BMW
    Toyota