PHP Arrays

PHP arrays are a variable that holds more than one value within a single variable. Generally, the element of the array will be of the same data type.

Kinds Of PHP Arrays

  • Indexed array: It is An array with a numeric index.
  • Associative array: It is also an array in which each key is associated with a value.
  • Multidimensional array: It is an array containing more than one array.

How To Declare PHP Array?

There are two ways to represent PHP arrays. These are:

  • Creating Array Using array() Function.
  • Creating Array using [ and ]

Let us see the associated example.

Source Code

          <?php
$array = array('Apple', 'Banana', 'Orange', 'Mango');
var_dump($array);
$array = ['Apple', 'Banana', 'Orange', 'Mango'];
var_dump($array);
?>
        
Try it now

PHP Indexed Arrays

An indexed or numeric array is very useful for storing each array element with a numeric index. By default array index starts from 0 indexes and the last element index number is (array length-1).

To create an indexed array, pass multiple values inside the PHP array() function and separate each value with a comma ,.

General Syntax

      array(Value1, Value2, ValueN);
    
Try it now

Source Code

          <?php
$fruits = ['Apple', 'Banana', 'Orange', 'Mango'];
$fruits[0] = 'Apple';
$fruits[1] = 'Banana';
$fruits[2] = 'Orange';
$fruits[3] = 'Mango';
?>
        
Try it now

Remember: Indexes start from 0, not 1.

Index array element can be access through: $arrayName[index]

PHP Indexed Array Example

Source Code

          <?php
$fruits = ['Apple', 'Banana', 'Orange', 'Mango'];
echo "First Fruit is $fruits[0]" . '<br>';  
echo "Second Fruit is $fruits[1]" . '<br>';
echo "Third Fruit is $fruits[2]" . '<br>';
echo "Forth Fruit is $fruits[3]" . '<br>';
?>
        
Try it now

Associative Arrays

PHP associative array has named keys that contain the values.

Creating an associative array using two ways:

1:An associative array can be created using the array() function or [].

Source Code

          <?php
$fruit = array(
	'mango' => 22,
	'orange' => 25,
	'apple' => 30
);
?>
        
Try it now

Web Tutorials

PHP Arrays
Html Tutorial HTML
Javascript Tutorial JAVASCRIPT
Css Tutorial CSS
Bootstrap 5 Tutorial BOOTSTRAP 5
Bootstrap 4 Tutorial BOOTSTRAP 4