8 minutes to read, 4.86K views since 2016.10.11

Working with arrays in php5

Preface

PHP arrays are one of the most powerful datastructure i've ever seen in programming languages:). Yup, that's true. You can work with different types of data across different areas of your application.

An array is basically a holder for multiple types of data and values. Instead of assigning a single value to a variable you can assign multiple values to an array and assign that array to a variable. What this means is you can group multiple values together in a variable and reference what you need when you need. If you start to do a lot of programming you will quickly see that arrays are incredibly powerful tools and you can use things like loops to output complex arrays with multiple values of different data types.

Array is a complex datatype which allows you to carry out some complex data in one variable. Lets consider a situation when you have a program when the products in warehouse are listed. Every product has common set of attibutes like price, name and quantity on warehouse for example. To desrcibe a product you must have a three variables: for its name, price and quantity:

Initialization

We can initialize empty array by short syntax which comes in php 5.3:

<?php

$products = [];

and older syntax which works in all versions of php:

<?php

$products = array();
    $p1_name = 'apple macintosh';
    $p1_price = 1.99;
    $p1_qty = 250;

Thats ok, but what if you have a lot of products? You need a lot of variables! But there is a solution: arrays. Arrays are used to carry out much similar information. The example solution of carrying data on products in array:

    $product = []; // declare an array for our product
    $product['price'] = 1.99; // assign value 1.99 to array’s index price 
    $product['name'] = 'Apple Macintosh';
    $product['qty'] = 250;

Its better that using three variables, am I right ? The beautiful property of arrays is that they can have nested structure. So you can have array of arrays and so on, this means you can put all your products to one array:

    $products = [];

    $product = [];
    $product['name'] = 'book';
    // other properties initialization goes here

    $product2 = [];
    $product2['name'] = 'phone';
    // ..

    $products['book'] = $product;
    $products['phone'] = $product2;

What have we done below? We put two products into one array. Now we have so called multidimensional array with two products inside. You can manipulate data in arrays as with simple variable. To get some part of an array use square brackets – operator of getting array’s index right after array’s name:


    $products['phone']['price'] += 100; // increase a price of a phone product by 100
    $products['book']['name'] = 'Some another book name'; // change book’s name

As I mentioned before, one of the most commonly used string functions is explode. It used to get substrings of a string separated with some delimiter. For example you have a text separated by dots. You can get array of sentences with explode. Lets have a look into another example: you have a list of numbers separated by comma and you want to get them into array:

    $numbers = '1,-2,509';
    $numbersArray = explode(',',$numbers); // now $numbersArray consists of 1, -2 and 509

Associative and not

In most languages with strict typing,array is a data structure which represents a number of similar items: for example integers or strings. As php is dynamically typed language it allows you to put into variable a float at first and then write a string into it. So, to access some element into array in c language for example you should use its numeric index (and no exceptions!). In php, you can use a string as an array element index - such arrays called associative, because they make association between string key and element of an array. So, arrays in php is not like an array in c++ or java. Analog of array in php in java are HashMap<String,SomeType>s.

Adding elements to array

Arrays in php has flexible size. Its mean that you don't need to declare the size of an array before its creation like in java for example.

There is two ways to put data into array: You can put data right into some index of an array. Index of an array can be a number (numeric index) and string (alphanumberic index)

    $products['some_product] = $phone;

You can put data at the end of an array:

    $products[] = $phone;

What does it mean at the end ? It means that index of an array would be created automatically. Php creates automatically numeric indexes:

    $products = [];
    $products[] = 1; // this creates index 0 : $products[0]

If you put at the end of array a value and you already had some value with alphanumeric index will be the minimum possible numeric index in array:

    $products = [];
    $products['some'] = 'thing';
    $products[] = 1; // this creates $products[0], even though there are data on index "some";

you can also use a function to add an element to array, for example:

    $p = [];
    array_push($p,'some product'); // creates $p[0]

you can add any elements to arrays, including arrays themselves. So you can build different complex structures which consists of arrays of arrays and so on, there is no visible restrictions (In fact, they are :))

Deleting elements

What if we want to remove some element? In that case we must use a language structure unset. To remove some index of an array you should use unset function:

    unset($a["some_index"]);

       // remove some deeply elements
        unset($a['some']['index']);

Counting elements

to get count elements of an array you can use count($array) function:

    $p = [];
    echo count($p); // 0
    p[0] = 'piano';
    echo count($p); // 1

you can check if some index of an array exists by using a function isset($a[0]):

    if (isset($a[0])) {
        echo 'index 0 exists in array a';;
    }

also you can check if some element of an array is empty or not:

    if (!empty($a[0])) {
        // do some actions 
    }   

usefull array functions

There are a lot of usefull functions to work with php from the box. They are (and not limited to):

    array_keys($a); // get array of indexes of an array
    array_unique($a); // removes repeating values from array
    array_merge($a,$b); // merges values of arrays
    shuffle($a); // randomly shuffles an array
    sort($a);
    in_array($value, array $a);

One of the most usefull functions with arrays is print_r which outputs content of an array in readable view. It's commonly used with debug need by many enthusiasts:

    print_r($a); 

will produce next output :

    Array
    (
        [another] => another index 
        [0] => 0s element
    )

Conclusion

We have very briefly revised array functions and features in php, actually that enough to build your own startup!

Read next article Functions in course Basic PHP