PHP Arrays

This is an introduction to PHP arrays, so if you are new to the language Clinica Stomatologie Bucuresti curs valutar crama lechinta Psiholog Cluj or you just need a refresher you can get up to speed pretty fast.

This is how we initialize an empty array and add some elements to it:

$chars = array();
array_push($chars,'a','b','c');

Then we can see it’s contents using the print_r() function. You may want to put this between <pre> tags for better formatting.

print_r($chars);

Output:

Array
(
    [0] => a
    [1] => b
    [2] => c
)

Another useful operation with arrays is knowing how many elements it contains. For that we can use the count() function.

$size = count($chars);
echo $size;
echo "";

One thing worth noting about php arrays is that they behave like hash maps. Because arrays are just key/value pairs, we can add a new pair like this:

$chars['name'] = 'John';

Now let’s see how we can iterate through arrays, using the foreach() function.

Looping through php arrays

foreach ($chars as $char) {
    echo $char;
    echo "";
}

If we also want the keys and not just the values, we can do this:

foreach ($chars as $key =>; $value ) {
    echo "Key: " . $key . " Value: ". $value;
    echo "";
}

Output:

Key: 0 Value: a
Key: 1 Value: b
Key: 2 Value: c
Key: name Value: John

You can download the example code here:
https://gist.github.com/3801039

Array function reference: http://php.net/manual/en/ref.array.php

Tags: arrays, php, programming

Popular posts