Array

0 wandadendy05874 December 10, 2020

An array is a group of related data items that share a common name. In the other words, an array is a data structure that stores a number of data items as a single entity (object). The individual data items are called elements and all of them have some data types. It is used when multiple data items that have common characteristics are required.

Syntax

We can create an array using array() function. We can declare the array in PHP as shown below:

array(
    key1 => $value1,
    key2 => $value2,
    key3 => $value3,
    .........
)

It is optional to use a comma in the last element. We can use [] instead of array(). Let’s look at one example to make clear concepts.

<?php

$demo = array(
    "program" => "PHP",
    "best" => "Python"
);

//we can use short array syntax
$demo = [
    "program" => "PHP",
    "best" => "Python"
];

?>

For the key, we use an array that may be integer or string. Usually, Keys in arrays are stored in the following ways.

  • If the key contains the valid decimal integer then it treats as int type. eg: “9” will treat as 9 as an integer.
  • Floats are also treated as integers. Such as 9.4 is also treated as 9.
  • Boolean in the arrays stores in the form of an integer. true stores as 1 and false stores as 0.
  • null uses as an empty string. Both “” and null works the same.

Note: If we use multiple elements with the same key then the last one will exist and others are over-written.

<?php

     $array = array(
          1    => "Code Help Pro",
         "1"   => "Language",
          1.5  => "Welcome",
          true => "Program"
     );
     var_dump($array);

?>

The output of the above program is

array(1){
    [1] => string(7) "Program"
}

All the above program index are treated as 1. So, All the are overwritten and last element with same key was overwritten.

Indexed arrays without key

The key that we use is optional. If we do not specify a key then PHP will automatically set the key with an incrementing number. Let’s look and example to make clear concepts.

<?php

$array = array("Code", "Help", "Pro", "Welcome");
var_dump($array);

?>

The output of above program is

array(4){
    [0] => string(4)Code,
    [1] => string(4)Help,
    [2] => string(3)Pro,
    [3] => string(7)Welcome
}

Access Array Elements

We can access the element using brackets signs. Let’s take an example to make clear concepts.

<?php

$array = array(
    "Learn" => array("Code", "Help", "Pro"),
    "Program" => "PHP"
);

var_dump($array["Program"]);
var_dump($array["Learn"][1]);

?>

The output of the above program is

string(3)PHP
string(4)Help

Note: We can use square brackets and curly braces for accessing the array elements. e.g. $array[“Learn”] and $array{“Learn”} will do the same thing.