Lesson 4 - Strings and arrays in PHP
In the previous lesson, Variables and type system in PHP, we talked about variables. In today's lesson, we're going to continue on and introduce you to arrays.
String declarations and escaping
Last time, we showed you how to declare strings. You now know that you can write them in apostrophes or quotation marks. To really get a solid understanding, we'll go over the difference between the two.
Apostrophes
If we write a string using apostrophes (single quotation marks), PHP will assign the text exactly as it is written:
{PHP}
$name = 'Carl';
$text = 'My name is $name \n I am satisfied with this "name".';
echo($text);
{/PHP}
The output:
PHP completely ignores dollar marks $, double quotes and backslashes (I'll explain why in a little bit).
If you wanted to insert a variable into a string that is written in single quotes, you have no other choice than using the dot operator.
{PHP}
$name = 'Carl';
$text = 'My name is ' . $name . ' \n I am satisfied with this "name".';
echo($text);
{/PHP}
A real advantage of using single quotes to declare text is that we can insert double quotes into single quoted strings which are useful when printing HTML code. This also proves useful when declaring HTML attributes (which are declared using double quotes):
{PHP}
echo('I am learning PHP using tutorials at <a href="http://www.ict.social">ict.social</a>.');
{/PHP}
If we wanted to insert an apostrophe in that text, we'd need to "escape" it so that PHP wouldn't mistake the apostrophe for the end of the string declaration. We "escape" characters using a backslash:
{PHP}
$text = 'It took me a while until I found the characters ", \' and ; on the keyboard.';
echo($text);
{/PHP}
The variable now has the following content:
It took me a while until I found the characters ", ' and ; on the keyboard.
Quotation marks
Now, let's take a look at double quotes and see what they're good for. In PHP, double quotes are "smarter" than single quotes and allow us to insert variables into strings easily:
{PHP}
$name = 'Carl';
$text = "My name is $name \nI'm satisfied with this name.";
echo($text);
{/PHP}
The output will be as follows (in the generated HTML code, a new line will be ignored by the browser):
My name is Carl I'm satisfied with this name.
The value of the $name variable was inserted into the $text
variable. As you can see, the \n
sequence was not printed. That is
because we use \ when defining special characters. These characters include
\n
which makes a "new line", and \t
which is the
equivalent of hitting the tab button on your keyboard. \n
won't
display in HTML but if you check your website's source code, you will find a new
line there.
Processing a string in double quotes is a bit slower due to variables handling, but you won't see it affect your applications at a noticeable level. Feel free to use the declaration that fits your current needs. Double quotes might not the best choice for printing HTML. However, you could easily write stuff in single quotes in a double quoted string, just remember that they have to be escaped:
{PHP}
echo("I'm learning PHP from courses at <a href=\"http://www.ict.social\">ict.social</a>.");
{/PHP}
The example above is very confusing. Personally, I prefer using single quotes and concatenating variables with dots. It seems more readable to me.
For completeness' sake, know that if you ever need to write a backslash in a single quoted string, you will have to make write two in a row \\. Otherwise, PHP would think you're escaping something.
Arrays
Imagine that you need to store several variables of the same type in your
application. It may be the names of each of the months, 10 school grades,
paychecks for 100 staff members or a database of 1000 companies. As you may have
expected, there is a better way than having to declare variables individually
like grade1
, grade2
, grade3
... and what
if our program had to handle 1000 marks? How would you compute the average of
each and every one of those variables?
PHP offers a data structure for storing multiple variables of the same type, known as arrays. There are two types of arrays in PHP. Let's go ahead and get into the first one.
Indexed arrays
One could imagine and indexed array as a row of boxes somewhere in computer memory (it actually looks like that by the way). The boxes are numbered starting with 0 and their numbers are called indexes. In programming, everything starts with zero - you may have heard that the first child of a programmer is actually the zeroth one We can have as many boxes as we want and can store values of any type. We can even have a number in one box and text in another. However, we try to keep variables of the same type separated for the sake of readability.
In the picture below you can see an array that stores 8 numbers:
Let's program something like that, we'll create an array of grades as I mentioned before. We'll enter all of the grades into the script since you don't know how to create forms yet. That is something we will go over in the next lesson
We'll store the array into a regular variable, name it in plural and based on
what's inside (which in this case is $grades
). We use the array
keyword when declaring an array()
.
$grades = array();
Now we have an empty array in the $grades
variable. If you're
using PHP 5.4 or above, you can also declare an array like this:
$grades = [];
This way is shorter and better in general, but I will stick with the older one because some readers may be using older web hosts.
Adding array elements
Let's add few grades now. As you may have expected, there are several ways of doing it.
We add a new element at the end of an array like this:
$grades[] = 1; $grades[] = 2; $grades[] = 5;
Our array now looks like this:
1, 2, 5
The echo()
function isn't very helpful when it comes to printing
arrays, which is why we have the print_r()
:
{PHP}
$grades = array();
$grades[] = 1;
$grades[] = 2;
$grades[] = 5;
print_r($grades);
{/PHP}
We can also insert an element at a specified index in the array. If there is already an element at this index, it will be overwritten.
$grades[0] = 1; $grades[1] = 3; $grades[2] = 5; $grades[1] = 2; // Overwrites the element at index 1 (value of 3) with a value of 2
The last line inserts an element of with a value of 2
at index
1
. Doing so will overwrite the value 3
, which was
previously there on the second line. This doesn't have an objective point, in
this case, I'm just showing you what arrays can do That text after the double slashes
is a comment. PHP completely ignores the comments and will not mistake them for
code under any circumstance. Comments are used by programmers to improve
readability and to document their code. I highly recommend using them when it
makes sense to. They could also be written in multiple lines, like this:
/*
This text is ignored by PHP and
this applies up to the end of the comment block.
This is how we can describe complicated parts of the program,
so we won't what we did there after a few months :)
*/
If we already knew what grades we need to set in the array, we could declare it with the content already stored within it.
$grades = array(1, 2, 3, 4, 2, 2, 1, 3, 2, 5);
Reading array values
If we needed to read a value from an array, we would use the value's index:
{PHP}
$grades = array(1, 2, 3, 4, 2, 2, 1, 3, 2, 5);
echo('The third grade in array is ' . $grades[2]);
{/PHP}
The output:
Practical array examples
PHP provides a lot of functions to work with arrays. We'll talk about them in the next couple of lessons. For the mean time, a couple will suffice:
Grade average
With the help of the array_sum()
and count()
functions, we can compute the average of our grades:
{PHP}
$grades = array(1, 2, 3, 4, 2, 2, 1, 3, 2, 5);
$average = array_sum($grades) / count($grades);
echo('My average is: ' . $average);
{/PHP}
The program output:
You can imagine how unreadable the program would be if it weren't for arrays
and ended up writing something like $sum = $mark1
+
$mark2
+ $mark3
... Here, we've easily divided the sum
of the array elements by their count.
English dates
As I have already said, we can insert anything into an array, the names of the months for example. We use this to print user-friendly dates in English (or whatever your native language is):
{PHP}
$months = array('January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December');
$day = date('j');
$month = date('m');
$monthInWords = $months[$month - 1];
$year = date('Y');
echo("Hello, today is $day $monthInWords, $year");
{/PHP}
Here, we created an array of the names of the months. Then, using the
date()
function we find today's date in numbers. Next, we assign
the name of the current month to the $monthInWords
variable. When
it's October for example (the 10th month), a value 10
would be
assigned to the $month
variable, but we need to set the element
with the value "October"
in $monthInWords
at index
9
because array elements are indexed from zero. For this reason, we
read from a "box" with the index set to $month - 1
. Last of all, we
print the variables' contents. We'll go over how to work with date and time in
further detail later on.
The output:
We'll return to arrays several times throughout the course, as there is still a lot of content left to cover. At this point, you surely get the gist of it, which is good. In the next lesson, Solved tasks for PHP lesson 1-4, we'll program our first form application, a simple calculator.
In the following exercise, Solved tasks for PHP lesson 1-4, we're gonna practice our knowledge from previous lessons.