PHP Array

PHP array is an variable which stores the multiple values of related data in a single variable.

 

Creating an PHP array

array() function is used to create an array.
The key can either be an integer or a string. The value can be of any type.
It takes any number of comma-separated key => value pairs as arguments.

 

Types of array

 

For example:

 

  • An array index can be any string value, even a value that is also a value in the array.
    The value of array[“foo”] is “bar”.
    The value of array[“bar”] is “foo”
  • The comma after the last array element is optional.
    This is usually done when you want to single-line array like array(1,2).
    It is preferred than writing array(1,2,).
    But for multi-line array is is commonly used because it is easier to add new element at the end of array.
    In previous of PHP 5.4 you have to use array() like this, but as of PHP5.4, array() is replace with array[].
    For example:
  • The key is optional. If it is not specified, PHP will use the increment of the largest previously used integer key.
    For example:

    Output:
  • You can specify only key for some elements and leave others.
    For example:

    Output:

    Here, you can see from output the last value “d” was assigned the key 4.
    This is because PHP increment the previous integer key i.e. 3.

 

Ankit Wasankar

Senior Java Developer
Java 11 | Microservices | Reactjs | SQL

Help others by sharing the content!

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.