Arrays in PHP:

In PHP arrays are special variables that can hold similar type of values in a single variable. For example if you want to store 200 names than creating 200 variables is not a good idea. You can define an array for that instead creating 200 variables.

There are three types of arrays and each array value is accessed by ID and the ID is called the array index.

  • Indexed Arrays
  • Associative Arrays
  • Multidimensional Arrays

 Indexed Arrays:

Indexed array means array with a numeric number. An array can store string, numbers and any objects and indexed array will represent it in a number. By default it starts from zero.

There are two ways to define Indexed Array:

  • Automatically assigned indexed array

Example:

$name = array(“John”, “Kim”,”Jeny”,”Roy”);

  • Manually assigned indexed array

Example:

$name[0] = “John”;

$name[1] = “Kim”;

$name[2] = “Jeny”;

$name[3] = “Roy”;

Example:

 The count() Function :

If you want to get the length of an array so in PHP we have count() function which will return the length.

Example:

 Loop in Indexed Array:

You can also print the values of array through the loop.

Example:

 Associative Arrays:

In associative array we will use index as a string. The functionality of Indexed array and Associative array is same. Associative array helps to establish a strong connection between key and value.

There are two ways to define Indexed Array:

  • First way to create array:

Example:

$user = array(“John”=>”2000”, “Kim”=>”3500”,”Jeny”=>”5000”);

  • Second way to create array

Example:

$user[‘John’] = “2000”;

$user[‘Kim’] = “3500”;

$user[‘Jeny’] = “5000”;

Example:

 Loop in Associative Array:

You can also print the values of associative array through the loop for that you have to use foreach loop which we already learn in our “For Loop” tutorial.

Example:

 Multidimensional Arrays:

In multidimensional arrays you can create an array for the main array also and also for sub arrays you can create array and so on. Values of multidimensional arrays can be accessed by using multiple indexes.

Example:

 

Leave a Reply

Your email address will not be published. Required fields are marked *