Arrays

What's an array, you say?

An array is a special kind of variable that can store multiple values in a single variable.

<?php
 $friends = array();
?>

Huzzah! We just created an array with array(), the so-called array constructor.

Values

An empty array doesn't really serve a purpose, though. How about we give $friends some values?

<?php
 $friends = array("Caroline", "Max");
?>

Great! We can create an array with values by putting them in the parentheses of array().

Accessing

But how can we access the contents of an array?

<?php
 $friends = array("Caroline", "Max");
 echo $friends[0];
?>

//Output Below

Caroline

That's it! We can access a value by putting its position in brackets after the array's name.

Psst: this position is zero-based, which means that it starts at 0.

Adding

We can also add values to an array. Let's add something to $friends, shall we?

<?php
 $friends = array("Caroline", "Max");
$friends[] = "Earl";
?>

Nice! We can add a value by giving it to the array with brackets but without a position.

Replacing

Now that we know how to add values, how might we be able to replace one?

<?php
 $friends = array("Caroline", "Max");
 $friends[1]  = "Chestnut";
 var_dump($friends);
?>

//Output Below

array(2) {
 [0]=>
  string(8) "Caroline"
  [1]=>
  string(8) "Chestnut"
}

Fantastic! We can replace a value by storing a new value at a position that already exists.

Psst: var_dump() is a so-called function that displays information about a variable. It allows us to see the whole array.

Counting

We can find out the number of items in an array as well. How might we do this?

<?php
 $friends = array("Caroline", "Max");
 echo count($friends);
?>

//Output Below

2

Sweet! We can use the count() function to find out how many values an array has.

Sorting

We can also sort an array. Let's add some more values and get $friends in alphabetical order!

<?php
 $friends = array("Caroline",
  "Max", "Earl", "Oleg", "Han");
sort($friends);
 var_dump($friends);
?>

//Output Below

array(5) {
  [0]=>
  string(8) "Caroline"
  [1]=>
  string(4) "Earl"
  [2]=>
  string(3) "Han"
  [3]=>
  string(3) "Max"
  [4]=>
  string(4) "Oleg"
}

Right on! The sort() function orders the items of an array in ascending order, be they numbers or strings.

Psst: another function called rsort() sorts an array in descending order.