6) Arrays

What is an Array?

All related values that are stored inside a variable is called an array.

Types of Array in PHP

  1. Indexed Array
  2. Associative array

Index Array:

Example for indexed array

To print indexed array

We can not use echo or print to print an array. We use a function <span class=”keyword”>print_r</span> to print an array

Example

Output :

Here each array element has a number starting from zero. This number is known as an array index. The array keyword is a traditional way to create an array in PHP.  But from PHP 5.4 you can use a shorthand to create an array. A new way of creating an array from PHP 5.4

Adding values to array operator.

When we run this PHP will automatically assign next available number to the elements of array added.

>>To display the second element of an array we will write

Associative Array:

In index array, we have a numeric index but in an associative array instead of numeric index, each array element is identified by a string. Associative array stores a set of key-value pair. Let’s look at the example

Note: Associative array works exactly the same as an indexed array. There is a major difference between an associative array and indexed array is you can not put an associative array inside double quotes.If you try doing that:

Example

When you run this you will get a fatal error. To get rid of this enclose associative array inside curly braces.

Now this code works fine