PHP

Arrays

All the variables you have used have held only a single value.
Array variables are “special” because they can hold more than one value in one single variable.
This makes them particularly useful for storing related values.

Types of Array

In PHP, There are three types of array.

  • Indexed array: An array with a numeric index.
  • Associative array: An array where each key is associated with a value.
  • Multidimensional array: An array containing one or more array.

Creating Array using array() Function

In PHP array can be created with array() function.

Syntax:

array(value1, value2, valueN);

This method is to create a numeric array. Here index are automatically assigned to array element.
All values are store in the form of array corresponding to their index value. i.e $arr[0] = value1, $arr[1] = value2 and so on.

Example:

<?php
    $arr = array(5, 10, 15, 20, 25);
    echo $arr[0];
?>

In the above example
All values are store in the form of array corresponding to their index value. i.e $arr[0] = 5, $arr[1] = 10, $arr[2] = 15, $arr[3] = 20, $arr[4] = 25.
we want to print first value of array, for this we call array name with their index ($arr[0]):

Output:

Tutorialik.com
5

Creating Array using Array identifier

This is second method to create a numeric array. Here also index assigned automatically.

Example:

<?php
    $arr[ ] = 5;
    $arr[ ] = 10;
    $arr[ ] = 15;
    $arr[ ] = 20;
    $arr[ ] = 25;
    echo $arr[0];
?>

Output:

Tutorialik.com
5

Creating Array using Array identifier: manually indexed

This method is also to create numeric array. But indexed assigned manually in this program.

Example:

<?php
    $arr[0] = 5;
    $arr[1] = 10;
    $arr[2] = 15;
    $arr[3] = 20;
    $arr[4] = 25;
    echo $arr[0];
?>

Output:

Tutorialik.com
5



Subscribe us on Youtube

Share This Page on


Ask Question