PHP Indexed Arrays

0
2K

PHP Indexed Arrays

In indexed arrays each item has an index number.

By default, the first item has index 0, the second item has item 1, etc.

ExampleGet your own PHP Server

Create and display an indexed array:

$cars = array("Volvo", "BMW", "Toyota");
var_dump($cars);
Try it Yourself »

Access Indexed Arrays

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

Example

Display the first array item:

$cars = array("Volvo", "BMW", "Toyota");
echo $cars[0];
Try it Yourself »

Change Value

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

Example

Change the value of the second item:

$cars = array("Volvo", "BMW", "Toyota");
$cars[1] = "Ford";
var_dump($cars);
Try it Yourself »

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:

$cars = array("Volvo", "BMW", "Toyota");
foreach ($cars as $x) {
  echo "$x <br>";
}
Try it Yourself »

For a complete reference of all array functions, go to our complete PHP Array Reference.



Index Number

The key of an indexed array is a number, by default the first item is 0 and the second is 1 etc., but there are exceptions.

New items get the next index number, meaning one higher than the highest existing index.

So if you have an array like this:

$cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota";

And if you use the array_push() function to add a new item, the new item will get the index 3:

Example

array_push($cars, "Ford");
var_dump($cars);
Try it Yourself »

But if you have an array with random index numbers, like this:

$cars[5] = "Volvo";
$cars[7] = "BMW";
$cars[14] = "Toyota";

And if you use the array_push() function to add a new item, what will be the index number of the new item?

Example

array_push($cars, "Ford");
var_dump($cars);
Try it Yourself »

PHP Exercises

Test Yourself With Exercises

Exercise:

Output the second item in the $fruits array.

$fruits = array("Apple", "Banana", "Orange");
echo ;

Start the Exercise

Cerca
Categorie
Leggi tutto
Altre informazioni
تطورات التعلم الآلي وتأثيرها على مستقبل العمل
مقدمة: في ظل التطورات السريعة للتكنولوجيا والابتكار، أصبح التعلم الآلي...
By MOHAMED ATTALLAH 2024-05-14 13:56:58 0 3K
Altre informazioni
الثورة البلوكتشين وتحولاتها في الصناعات المختلفة
مقدمة: شهدت تقنية البلوكتشين ثورة هائلة في السنوات الأخيرة، حيث أصبحت لديها القدرة على تغيير...
By MOHAMED ATTALLAH 2024-05-14 14:03:03 0 3K
Altre informazioni
PHP Array Functions
PHP Array Functions PHP has a set of built-in functions that you can use on arrays....
By PHP Tutorial 2024-05-17 08:07:42 1 4K
Altre informazioni
PHP Sorting Arrays
The elements in an array can be sorted in alphabetical or numerical order, descending or...
By PHP Tutorial 2024-05-17 08:06:46 0 3K
Altre informazioni
PHP Add Array Items
Add Array Item To add items to an existing array, you can use the bracket [] syntax....
By PHP Tutorial 2024-05-17 08:06:05 0 4K