My PHP journey part 5.

Arrays

An array, is a variable that has more than one value. This is known as a compound data type.

They’re useful because they can store stuff.

They look like this.

$months [0] = ‘January’;
$months [1] = ‘February’;
$months [2] = ‘March’;
$months [3] = ‘April’;
$months [4] = ‘May’;
$months [5] = ‘June’;
$months [6] = ‘July’;
$months [7] = ‘August’;
$months [8] = ‘September’;
$months [9] = ‘October’;
$months [10] = ‘November’;
$months [11] = ‘December’;

The number in the square brackets is the order of the values, fairly obvious – it does have a fancy name – ‘array operator’.

But they can so look like this, in which case php will assume the number for you – counting from zero…

$shopping = [
‘bread’,
‘milk’,
‘butter’,
‘pasta’,
‘cheese’,
‘bin bags’,
‘oranges’,
‘apples’,
‘washing up liquid’,
‘rice’
];

So if you were to

echo $shopping[0];

The ‘bread’ will appear.

An array operator can also be a string key. For example:

$dog[‘name’] = ‘rover’;
$dog[‘age’] = 3.5;
$dog[‘eats’] = ‘shoes’;

Indexed arrays

An indexed array will look like this:

Array
(
[0] => tidy house
[1] => walk dog
[2] => go shopping
)

Where as an associative array will look like this:

Array
(
[name] => rover
[age] => 3.5
[eats] => shoes
)

The hash rocket => (sounds cooler than what it actually is!) means in php “Has the property” but will mean something different in other scripting languages.

Associative Arrays

Much like the above indexed arrays – except you can let php do the some of the work.

They look a bit like this.

$nikki = array(
‘first_son’ => ‘Ryan’,
‘second_son’ => ‘Liam’,
‘third_son’ => ‘Callum’,
‘first_daughter’ => ‘Jessica’
);

//In English, this reads “Nikki has some children, her first is Ryan, her second son is Liam…” And so on. 

php is doing the indexing for you… Hooray!

 

Outputting arrays

It’s all well and good having arrays which store loads of data, but how do you get stuff out of them?

Okay so you have the following array:

$joe = [‘eats’ => ‘pizza’, 

‘siblings’ => ‘two brothers’, 

‘hobby’ => ‘hang gliding’];

You could then write a script which says:

<p>Joe’s favourite food is <?php echo $joe[‘eats’] ?>, which he likes to eat with his <?php echo
$joe[‘siblings’] ?> while <?php echo $joe[‘hobby’] ?></p> 

It’s the same with indexed arrays, except you’ll need to put the number instead of the word. (Some hardcore php-ers will say this looks clumsy – but at this stage it doesn’t matter).

Now there’s a whole bunch of stuff you can talk about on arrays, including extracting the values and the labels using a foreach construct, plus multi-dimensional arrays and nested arrays.  But I think I’ll save this for another blog post.  I’m still trying to get my head around the above!

Leave a Reply

Your email address will not be published. Required fields are marked *