CommonLounge Archive

PHP: Variables and Arrays

September 19, 2018

In the last tutorial, you learnt about PHP Files, Numbers, Strings and Functions. In this tutorial, you’ll learn about variables and arrays. Let’s get started!

Variables

An important concept in programming is variables. Variables are used to store values. We looked at it briefly in the previous tutorial. Now let’s actually try to understand more about it.

A good analogy for the variable is a box. You can imagine the name of the variable as the label on the box, and the value of the variable as what’s stored inside it.

Let’s create a new variable called name:

<?php
    $name = "Commonlounge";
?>

The above is equivalent to saying: Store the value "Commonlounge" in variable name.

To see the value inside a variable we can use echo like we have been using previously. Simply type in echo $name;, save the file and refresh the browser.

<?php
    $name = "Commonlounge";
    echo $name; // prints 'Commonlounge'
?>

You will see Commonlounge printed on your browser.

Of course, variables can be anything – numbers too! Try this:

<?php
    $name = 5;
    echo $name;    // prints 5
?>

You can always change the value stored inside the variable:

<?php
    $name = "Commonlounge";
    echo "<h1>" . $name . "</h1>"; // prints 'Commonlounge'
    $name = "David";
    echo "<h1>" . $name . "</h1>"; // prints 'David'
?>

Remember the concatenation (.) operation that we saw in the previous tutorial to add HTML tags while using echo?

When you store a new value in a variable, the old value gets tossed out. This means we can’t get back to "Commonlounge" again, unless we stored it in some other variable. For example:

<?php
    $name = "Commonlounge";
    $y = $name;
    echo "<h1>" . $y . "</h1>"; // prints 'Commonlounge'
    $name = "David";
    echo "<h1>" . $name . "</h1>"; // prints 'David'
    echo "<h1>" . $y . "</h1>"; // prints 'Commonlounge'
?>

Above, when we did $y = $name, y now has the value "Commonlounge" inside it. Then we updated the value of name to "David", but y is unchanged.

You can also use a variable to assign value to itself.

<?php
    $name = "Commonlounge";
    $name = "Hello" . $name . "!";
    echo "<h1>" . $name . "</h1>"; // prints 'Hello Commonlounge!'
?>

When you do $name = "Hello " . $name . "!", you are telling PHP to evaluate the expression "Hello " . $name . "!", and store the result in name.

Here’s another example:

<?php
    $a = 5;
    $a = $a * 3;
    echo "<h1>" . $a . "</h1>"; // prints 15
    $a = $a * $a;
    echo "<h1>" . $a . "</h1>"; // prints 225
?>

Awesome, right?


You can use variables in functions too:

<?php
    $name = "Commonlounge";
    echo "<h3>" . strlen($name) . "</h3>"; // prints 12
?>

Remember we said all expressions in PHP evaluate to a single value? The result of evaluating a variable is simply the value stored inside it. So, the step-by-step breakdown of evaluating the above expression would be:

"<h3>" . strlen($name) . "</h3>"
=> "<h3>" . strlen("Commonlounge") . "</h3>"   <— PHP looks up the value stored in variable "name"
=> "<h3>" . 12 . "<h3>"
=> "<h3>" . "12" . "<h3>"
=> "<h3>12" . "<h3>"
=> "<h3>12</h3>"

Here is an important thing to know about while creating a variable:

Variable names

A variable name:

  • must start with a letter or the underscore character. In particular, it cannot start with a number.
  • can only contain alphanumeric characters and underscores (A-Z, 0-9, and _ )
  • is case-sensitive ($age and $AGE are two different variables)

Errors

OK. So let’s create a variable starting with a number just to see what happens:

<?php
    $5mangoes = 10;
?>

This is the output you will see on your browser:

Parse error: syntax error, unexpected '5' (T_LNUMBER), expecting variable (T_VARIABLE) or '{' or '$' in...

We got our first error! Making mistakes (even intentional ones) are an important part of learning! In particular, an error doesn’t mean something bad is going to happen with the computer. It’s just PHP’s way of saying, “Something’s wrong.” or “I don’t understand.”

Here, PHP says unexpected '5' which means PHP did not expect a variable starting with a number and hence, it gives us a syntax error.

Play with this for a bit and see what you can do!

Indexed arrays

Beside strings and integers, PHP has all sorts of different types of data. Now we’re going to introduce one called arrays. Arrays can be thought of as a list of objects.

Let’s create an array of lottery numbers. We don’t want to repeat ourselves all the time, so we will put it in a variable, too:

<?php
    $lottery = [3, 42, 12, 19, 30, 59]; // or $lottery = array(3, 42, 12, 19, 30, 59);
?>

All right, we have an array! What can we do with it? Let’s see how many lottery numbers there are in an array. Do you have any idea which function you should use for that? You know this already!

echo count($lottery); // 6

Yes! count() function can give you the number of objects in an array. Handy, right? Maybe we will sort it now:

sort($lottery);

This doesn’t return anything, it just changed the order in which the numbers appear in the array. Let’s print it out again and see what happened:

var_dump($lottery); 
// array(6) { [0]=> int(3) [1]=> int(12) [2]=> int(19) [3]=> int(30) [4]=> int(42) [5]=> int(59) }

As you can see, the numbers in your array are now sorted from the lowest to highest value. Congrats!

The var_dump() function is used to display type and value about one or more variables.

Indexes

If you want to show only the first number, you can do this by using indexes. An index is the number that says where in an array an item occurs. Programmers prefer to start counting at 0, so the first object in your array is at index 0, the next one is at 1, and so on. Try this:

echo "<p>" . lottery[0] . "</p>";   // 3
echo "<p>" . lottery[1] . "</p>";  // 12

As you can see, you can access different objects in your array by using the array’s name and the object’s index inside of square brackets.

Adding and deleting elements

If you want to add a single element at the end of your array, you can do this by typing:

array_push($lottery, 88);
var_dump($lottery); 
// array(7) { [0]=> int(3) [1]=> int(12) [2]=> int(19) [3]=> int(30) [4]=> int(42) [5]=> int(59) [6]=> int(88)}
echo $lottery[6]; // prints 88

You can use the array_pop() function to delete the last item in the array.

<?php
    $a = array("red", "green", "blue");
    array_pop($a);
    var_dump($a); // prints array(2) { [0]=> string(3) "red" [1]=> string(5) "green" }
?>

As you can see from the output, the last element from the array has been deleted.


More array types

What you saw just now are actually called Indexed Arrays.

PHP supports three types of arrays:

  • Indexed arrays - Arrays with a numeric index
  • Associative arrays - Arrays with named keys
  • Multidimensional arrays - Arrays containing one or more arrays

Associative arrays

An associative array is similar to an indexed array, but you access values by looking up a key instead of a numeric index. A key can be any string or number.

Now, try writing the following code (try substituting your own information, too):

$participant = array(
    'name'=>'Commonlounge', 
    'country'=>'Canada', 
    'favorite_numbers'=>[7, 42, 92]
);

With this command, you just created a variable named participant with three key–value pairs:

  • The key name points to the value 'Commonlounge' (a string object),
  • country points to 'Canada' (another string),
  • and favorite_numbers points to [7, 42, 92] (an array with three numbers in it).

You can check the content of individual keys with this syntax:

echo $participant['name']; // prints 'Commonlounge'

See, it’s similar to an indexed array. But you don’t need to remember the index – just the name.

Notice for undefined key

OK. So now let’s have a look at what happens if we try to access a value using a key that doesn’t exist:

echo $participant['age'];

As expected, we should see something like this:

Notice: Undefined index: age in...

Since age was never defined in the participant array, PHP throws us a Notice.

A notice is an advisory message meaning “You probably shouldn’t be doing what you’re doing, but I’ll let you do it anyway”. Ideally, we don’t want notices in our web application.

When should you use an associative or an indexed array?

When should you use an associative or an indexed array? Well, that’s a good point to ponder. Just have a solution in mind before looking at the answer in the next line.

  • Do you just need an ordered sequence of items? Go for an indexed array.
  • Do you need to associate values with keys, so you can look them up efficiently (by key) later on? Use an associative array.

Adding and deleting elements

Associative arrays, like indexed arrays, are mutable, meaning that they can be changed after they are created. You can add new key–value pairs to an associative array after it is created, like this:

$participant['favorite_language'] = 'PHP';
echo $participant['favorite_language']; // prints 'PHP'

Like indexed arrays, using the count() method on the associative array returns the number of key–value pairs in the array. Go ahead and type in this command:

echo count($participant); // 4

To remove a key-value pair from an associative array, use the unset function, like so:

unset($participant['favorite_numbers']) // remove key 'favorite_numbers'
echo count($participant); // 3

You can also change a value associated with an already-created key in an associative array. Type this:

$participant['country'] = 'Germany';
echo $participant['country']; // prints 'Germany'

As you can see, the value of the key 'country' has been altered from 'Canada' to 'Germany'. 🙂 Exciting? Hurrah! You just learned another amazing thing.


Multidimensional arrays

In addition to being an associative array, the above array is also a multidimensional array. That’s because $participant['favorite_numbers'] is itself an array. That is, we have an array inside an array.

So, you can do:

echo $participant['favorite_numbers'][2]; // prints 92
echo $participant['favorite_numbers'][1]; // prints 42

Pretty neat, right?

Summary

Awesome! You know a lot about programming now. In this last part you learned about:

  • variables – names for objects that allow you to code more easily and to make your code more readable
  • arrays– lists of objects stored in a particular order
  • types of arrays – indexed, associative and multidimensional arrays.
  • errors and notices – you now know how to read and understand errors and notices that show up if PHP doesn’t understand a command you’ve given it

Excited for the next part? :)


© 2016-2022. All rights reserved.