PHP working with arrays

In this tutorial, you will learn Types of the array, How to make array and print array

PHP working with arrays

What is an Array?

The array is a  variable holds a set of values, each value is associated with a key and through it, you can access its value

How to make an array in PHP

The array can be defined by using [ ] or by using the array()  function

There are two ways to write an array:

  1. Without typing the key where Auto is defined as a sequential number starting from Index 0
    • $newArray=[value1,value2,value3];
    • $newArray=array(value1,value2,value3);
  2. Typing both key and value
    • $newArray=[

      key => value,

      key2 => value2,

      ];

    • $newArray=array(

      key => value,

      key2 => value2,

      );

 

doon`t forget to use quotes around a string in array index

If more than one element in the array has the same key, the last value will be used. Other similarities key will overwritten

 

Types of the array in PHP

 There are three types of array in PHP any of them can be used as needed:

  1. Indexed arrays 

    • value can be typed without having to type the key

    • $newArray=[1,2,3,4,5,6,7,8];
  2. Associative arrays 

    • The value can be of any data type but the key must be an integer or a string.
    • $newArray=[
      'one'=>1,
      'two'=>2,
      'three'=>3,
      'four'=>4
      ];
  3. Multidimensional arrays

    • This array type can contain one or more other array
    • $newArray=[
      'fruits'=>[
         'apple',
         'banana',
         'orange'
        ],
      'vegetables'=>[
         'carrot',
         'tomato'
         'lemon'
        ]
      ];

print PHP array print_r( )

Example 

 

$newArray=[1,2,3,4];

echo '<pre>';
print_r($newArray); 
echo '</pre>';
 
 

Last modified