PHP Indexed Arrays

An indexed array is an array where each element is assigned a numeric index. The index starts from 0 by default and increments by 1 for each subsequent element. Indexed arrays are typically used to store a simple list of items such as numbers, strings, or other data types.

Example
<!DOCTYPE html>
<html>
<body>
<?php
$fruits = array("Apple", "Banana", "Cherry");
var_dump($fruits);
?>
</body>
</html>

Try it yourself

Access Indexed Arrays


To access an element in an indexed array, you use its index inside square brackets:

Example
<!DOCTYPE html>
<html>
<body>
<?php
$fruits = ["Apple", "Banana", "Cherry"];
echo $fruits[0]; // Outputs: Apple
echo $fruits[1]; // Outputs: Banana
?>
</body>
</html>

Try it yourself

Change Value


You can change an element’s value by specifying its index:

Example
<!DOCTYPE html>
<html>
<body>
<?php
$fruits = ["Apple", "Banana", "Cherry"];
$fruits[1] = "Blueberry"; // Changes the element at index 1 to "Blueberry"
var_dump($fruits);
?>
</body>
</html>

Try it yourself

Loop Through an Indexed Array


You can loop through an indexed array using a foreach loop:

Example
<!DOCTYPE html>
<html>
<body>
<?php
$fruits = ["Apple", "Banana", "Cherry"];

foreach ($fruits as $fruit) {
echo $fruit . "<br>";
}
?>
</body>
</html>

Try it yourself


Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.