Learn PHP in One Day and Learn It Well

Chapter 5: More Data Types in PHP

In the previous chapter, we looked at some of the basic data types in PHP. In this chapter, we’ll discuss two more data types – strings and arrays. You can create a new file named chap5.php to test the examples in this chapter.

5.1 Strings

A string refers to a piece of text. In PHP, strings must be enclosed in single or double quotation marks. For instance, if we write

$msg = 'Hello';
$greeting = "Good Morning";
$emptyStr = "";

 $msg and $greeting store the strings 'Hello' and "Good Morning" respectively.

 $emptyStr , on the other hand, stores a special string known as an empty string. This is because there is no text enclosed within the pair of double quotation marks we assign to it.

In PHP, you can combine multiple strings using the concatenate operator (.). Let’s look at an example:

$areacode = "(208)";
$contact = '+1' . $areacode . '1234567';
echo $contact;

Here, we use the concatenate operator twice to concatenate the string '+1' , the variable $areacode and the string '1234567' to form a new string. I’ve added spaces before and after the concatenate operators so that you can see the three components more clearly; you do not need to add these spaces.

After concatenating, we assign the new string to a variable called $contact and use the echo statement to echo its value.

If you run the code above, you’ll get


as the output.

>5.1.1 Commonly used String Functions in PHP

Next, let’s discuss some of the commonly used string functions in PHP. PHP comes with a large number of built-in functions for working with strings. Most functions return a result after performing their tasks. We can assign the result to a variable or use the echo statement to display the result directly.

A function may have different variations as some functions allow us to provide optional arguments to modify the function’s behavior. The examples below discuss the most common and useful approach to using each function.


The strlen() function gives us the length of a string.


$str1 = 'Good Day!';
echo strlen($str1);



Here, we declare a variable called $str1 and assign the string 'Good Day!' to it. Next, we pass $str1 to strlen() and use the echo statement to display the function’s result directly.

We get 9 as the output because 4 ( 'Good' ) + 1 ( ' ' ) + 3 ( 'Day' ) + 1 ( '!' ) = 9.

strtolower(), strtoupper()

The strtolower() and strtoupper() functions convert a string to lowercase and uppercase respectively and return the new string. The original string is not changed.


$str2 = 'Hello World';
$str3 = strtolower($str2);
$str4 = strtoupper($str2);
echo '<BR>'.$str2;
echo '<BR>'.$str3;
echo '<BR>'.$str4;

Here, we declare a variable called $str2 and assign the string 'Hello World' to it. Next, we pass $str2 to strtolower() and strtoupper() and assign the results to $str3 and $str4 respectively.

Finally, we use three echo statements to echo the values of $str2$str3 and $str4 . In each case, we concatenate '<BR>' with the variable so that the output will start on a new line.

If you run the code above, you’ll get

Hello Worldhello worldHELLO WORLD

as the output.


The trim() function removes whitespaces from the front and end of a string by default and returns the new string. You can specify other characters for it to remove by passing a second optional argument to the function.

Example 1:

$str5 = ' is ';
echo 'PHP'.$str5.'Fun<BR>';
echo 'PHP'.trim($str5).'Fun<BR>';


PHP is Fun

Here, we first concatenate $str5 with the strings 'PHP' and 'Fun<BR>' and use an echo statement to echo the resulting string directly. We get “PHP is Fun” as the output.

Next, we use the trim() function to remove whitespaces from $str5 and concatenate it with 'PHP' and 'Fun<BR>' again.  We get “PHPisFun” as the output this time.

Example 2:

$str6 = '**Hello**World***';
echo trim($str6, '*');



Here, we pass '*' to the trim() function as the second argument. As a result, asterisks (instead of whitespaces) are removed from the front and back of $str6 and we get “Hello**World” as the output.


The substr() function returns a substring. To use this function, we need to pass two arguments to it – the string to extract the substring from and the position to start extracting it. We can also pass a third argument to specify the length of the substring to extract. If we do not provide this argument, the function extracts the substring starting from the specified starting position to the end of the string.

Positions in strings start from 0, not 1. For instance, if we have a string 'ABCDEF''A' is at position 0, 'B' is at position 1 and so on.

Positions can also be negative. If it is negative, it is counted from the back of the string. In 'ABCDEF''F' is at position -1, 'E' is at position -2 etc.


$str7 = 'ABCDEF';
echo substr($str7, 2).'<BR>';
echo substr($str7, -3).'<BR>';
echo substr($str7, 2, 1);



Here, we declare a variable called $str7 and assign the string 'ABCDEF' to it. Next, we pass $str7 to substr() thrice to extract different substrings from it.

In the first two examples, the substr() function extracts substrings starting from (and including) positions 2 and -3 respectively. Hence, we get “CDEF” and “DEF” as the outputs.

In the third example, we specify the desired length of the substring by passing a third optional argument to substr() . As we specify the desired length to be 1, we get “C” as the output. Got it?

We’ve covered several string functions in PHP. For a full list of all the string functions available, you can check out the pagehttps://www.php.net/manual/en/ref.strings.php.

5.2 Using Strings to Represent Dates

Next, let’s learn to use strings to represent dates. To do that, we use a built-in function called strtotime() .

5.2.1 The strtotime() function

As the name suggests, the strtotime() function converts a string to time. It accepts a string describing a specific date (and time) and tries to convert that to a timestamp.

If you pass a string to the function that it is unable to convert, it returns false . On the other hand, if you pass a string that it is able to convert, it parses the string and returns the UNIX timestamp.

A UNIX timestamp is an integer that gives us the number of seconds that have elapsed since January 1 1970 00:00:00 UTC.

For instance, if you run the statement

echo strtotime("next Monday");

you’ll get something similar to


This gives the UNIX timestamp for next Monday (at the time of writing).

The strtotime() function is quite smart and is able to convert various English textual datetime descriptions into UNIX timestamps. For instance, it has no problem converting strings like "now""tomorrow""next Monday""15 Nov 2019" or "+1 week" .

However, while the function is easy to use, you’ll probably agree that the timestamp it returns is not very useful in most cases. If you want to get a more meaningful format for a date or time, you can use another built-in function called date() .

5.2.2 The date() function

The date() function accepts an optional timestamp and formats the timestamp into a more readable string. If the timestamp is not provided, it formats the current timestamp.

Suppose we want to format a timestamp that is 10 hours from the current time, we can use the statement below:

echo date('d-M-Y', strtotime("+ 10 hours"));

Here, we pass two arguments to the function.

The first argument specifies how we want the timestamp to be formatted. To do that, we use a string consisting of punctuation marks and predefined characters (as defined onhttps://www.php.net/manual/en/function.date.php).

In our example, we use the string 'd-M-Y' .

The character ‘d’ indicates that we want the day to be represented as a two-digit number, using a leading zero if necessary (e.g., 3 is output as 03). The characters ‘M’ and ‘Y’ indicate that we want the month and year to be represented as a three-letter text (e.g., Jan) and a four-digit number respectively. Last but not least, the punctuation mark ‘-’ indicates that we want the day, month and year to be separated by hyphens.

After specifying the desired format, we pass a second argument ( strtotime("+ 10 hours") ) to the date() function. This argument is optional and specifies the date we want the function to format.

If you run the echo statement above, you’ll get an output similar to


This gives the date 10 hours from now (at the point of writing). Got it?

5.2.3 Setting the timezone

The sections above discussed two of the many built-in date/time functions in PHP. While most of these functions are easy to use, do note that their results are affected by the timezone set in our PHP server.

For instance, while

echo date('d-M-Y', strtotime("+ 10 hours"));

gives us 03-Apr-2020 in one timezone, it may give us 04-Apr-2020 in another.

To avoid any discrepancy in results, it is strongly recommended that you manually set the timezone in your PHP server if you want to use any date/time function in PHP.

To do that, you need to modify the date.timezone setting in php.ini. Refer to Chapter 2 for instructions on locating this file.

Once you have located the file, open it, and scroll to the bottom of the page.

Next, head over tohttps://www.php.net/manual/en/timezones.phpfor a list of valid timezone identifiers. Say you want PHP to use the New York timezone, you need to add the line


to the bottom of php.ini. Once that is done, save the file, restart Apache, and the setting will be updated. Got it?

If you do not have permission to update the php.ini file, you can use the date_default_timezone_set() function. This function takes a timezone identifier and sets the default timezone used by all date/time functions in a PHP script.

For instance, to set the default timezone to the New York timezone, simply add


to the start of your PHP script. This affects the timezone for that particular PHP script. If you want another PHP script to use the same timezone, you have to set it in that script too.

5.3 Arrays

Great! Now that we are familiar with strings and dates, let’s move on to another commonly used data type in PHP – arrays.

An array is a special data type that allows us to store related values together as a single variable.

For instance, suppose you want to store the test scores of 5 students. Instead of storing them as $marks1$marks2$marks3$marks4 and $marks5 , you can store them as an array.

5.3.1 Creating an Array

There are a few ways to create an array in PHP; the most common way is to use the array() function.

Example 1

$firstArr = array();

This creates an empty array.

Example 2

$secondArr = array(11, 16, 4, 9, 12);

This creates an array with 5 elements (i.e. 5 values).

The array created is known as an indexed array, as each element in the array has an index.

Indexes start from 0. In other words, the first element ( 11 ) has an index of 0, the second ( 16 ) has an index of 1, and so on.

To access the individual elements in the array, we use its index and a pair of square brackets. For instance, if you write

echo $secondArr[3];

you are accessing the 4th element; you’ll get 9 as the output. You can also use the index to update the value of an element.

$secondArr[3] = 20;

updates the 4th element to 20 .

 $secondArr becomes (11, 16, 4, 20, 12)

Example 3

In addition to storing numbers, arrays can be used to store other data types. In the example below, $fruitsArr is used to store strings.

$fruitsArr = array('Apple', 'Banana', 'Coconut');

Example 4

Besides indexed arrays, we can create associative arrays. An associative array is one where each value in the array is associated with a key. For instance, in the example below, the value 16 is associated with 'Jane' (known as its key).

$assocArr = array(
	'Peter' => 11,
	'Jane' => 16,
	'Paul' => 12

To access the values in an associative array, we use its key. If we write

echo $assocArr['Paul'];

we’ll get 12 as the output.

Example 5

Next, arrays can be used to store arrays. This is known as a multidimensional array.

$simpleMDArr = array(
	array(1, 2, 1, 4, 5),
	array(0, 5, 1, 3, 4),
	array(4, 1, 7, 8, 9)

In the example above,

 $simpleMDArr[0] stores the array (1, 2, 1, 4, 5)$simpleMDArr[1] stores (0, 5, 1, 3, 4) , and $simpleMDArr[2] stores (4, 1, 7, 8, 9) .

If you want to access the elements in the “inner” arrays, you use two pairs of square brackets. For instance,

echo $simpleMDArr[2][3];

gives us the 4th (3+1) element in $simpleMDArr[2] . We’ll get 8 as the output.

Example 6

Associative arrays can also be used to store arrays. In the example below, $assocMDArr is an associative array used to store three indexed arrays.

$assocMDArr = array(
	"first array" => array(1, 2, 6, 1, 3),
	"second array" => array(3, 5, 1, 8, 9),
	"third array" => array(1, 0, 9, 4, 7)

 $assocMDArr["first array"] stores the array (1, 2, 6, 1, 3) .

If we write echo $assocMDArr["first array"][2]; we’ll get the 3rd element in $assocMDArr["first array"] . In other words, we’ll get 6 as the output.

Example 7

Last but not least, we can use an associative array to store associative arrays.

$anotherAssocMDArr = array(
	"first player" => array("name" => 'John', "age" => 25),
 	"second player" => array("name" => 'Tim', "age" => 35)

In the example above, $anotherAssocMDArr["first player"] stores the array ("name" => 'John', "age" => 25) .

If we write echo $anotherAssocMDArr["first player"]["age"]; we’ll get 25 as the output.

5.3.2 Displaying the Content of Arrays

Next, let’s learn two convenient ways to display the content of arrays.

One way is to use the var_dump() function covered in the previous chapter. This function displays the data type and value of a variable. If we write

$myArray = array(2, 5.1, 'PHP', 105);

we’ll get

array(4) { [0]=> int(2) [1]=> float(5.1) [2]=> string(3) "PHP" [3]=> int(105) }

as the output.

“array(4)” indicates that $myArray is an array with 4 elements.

The text inside the pair of braces that follows indicates the data type and value of each element. For instance, “[0] => int(2)” tells us that the element at index 0 is an integer of value 2 , “[1] => float(5.1)” tells us that the element at index 1 is a float of value 5.1 and so on.

Next, we have the print_r() function.

This function is similar to the var_dump() function. However, its output is more concise as it does not give us the data type of each element. For instance,


gives us the following output:

Array ( [0] => 2 [1] => 5.1 [2] => PHP [3] => 105 )

5.3.3 Adding Elements to Arrays

After creating an array, we can add new elements to it. There are a few ways to do it. The easiest is to use the square bracket notation. This notation allows us to add one element at a time to an array.

Example 1

$addDemo = array(1, 5, 3, 9);
	$addDemo[] = 7;

In the example above, we add 7 to $addDemo . The array becomes (1, 5, 3, 9, 7) .

Example 2

$addDemoAssoc = array('Peter'=>20, 'Jane'=>15);
$addDemoAssoc['James'] = 17;

Here, we add 'James'=>17 to $addDemoAssoc . The array becomes ('Peter'=>20, 'Jane'=>15, 'James'=>17) .

5.3.4 Deleting Elements from Arrays

Besides adding elements to arrays, we can delete elements from them. One way is to use the array_splice() function.

To use this function, we need to pass two arguments to it – the array to remove elements from and the position to start removing them.

We can also pass a third argument to specify the number of elements to remove. If we do not provide this argument, the function removes all elements from the specified starting position to the end of the array.

Let’s look at some examples.

Example 1

$colors = array("red", "black", "pink", "white");
	array_splice($colors, 2);

Here, we indicate that we want array_splice() to remove all elements from $colors , starting from (and including) the element at position 2.

 $colors becomes ("red", "black") .

Example 2

$awardwinners = array("Gold"=>"Max", "Silver"=>"Boots", "Bronze"=>"Dora");
array_splice($awardwinners, 1);

Here, we want array_splice() to remove all elements from $awardwinners , starting from (and including) position 1.

 $awardwinners becomes ( "Gold"=>"Max" ).

Example 3

$pets = array("corgi", "poodle", "golden retriever", "jack russell");
array_splice($pets, 1, 2);

Here, we want to remove 2 elements from $pets , starting from (and including) position 1.

 $pets becomes ("corgi", "jack russell") .

5.3.5 Commonly used Array Functions in PHP

We’ve covered several array concepts in the previous sections. Before we end this chapter, let’s look at some commonly used array functions in PHP.


The first is the count() function. This function accepts an array and returns the number of elements in the array.


$countDemo = array(1, 4, 5, 1, 2);
echo count($countDemo);




Next, we have the array_search() function. This function searches for a particular value in an array. If the value is found, the function returns its corresponding index or key. Else, it returns false . If more than one instance of the value is found, the index or key of the first matching value is returned.


$indexArrDemo = array(11, 4, 5, 1, 2, 5, 6);
$assocArrDemo = array('A'=>12, 'B'=>5, 'C'=>20);

echo array_search(5, $indexArrDemo).'<BR>';
echo array_search(20, $assocArrDemo).'<BR>';
var_dump(array_search('B', $assocArrDemo));



In the first echo statement above, we use the array_search () function to search for 5 in $indexArrDemo . Although there are two values of 5 in the array, only the index of the first matching value is returned.

In the second echo statement above, we use array_search () to search for 20 in $assocArrDemo . We get “C” as the output.

In the last echo statement, we use array_search () to search for 'B' in $assocArrDemo . We get false as 'B' is a key in the array, not a value.


The in_array() function is similar to the array_search() function. However, instead of returning the key or index, it returns true if the stated value is found in the array. Else, it returns false .

With reference to $indexArrDemo and $assocArrDemo defined above,

var_dump(in_array(5, $indexArrDemo));
var_dump(in_array(20, $assocArrDemo));
var_dump(in_array('B', $assocArrDemo));

give us

bool(true) bool(true) bool(false)

as the output.


Finally, we have the array_merge() function. This function merges two or more arrays and returns the merged array.

Example 1:

$num1 = array(100, 111, 120);
$num2 = array(100, 3, 5);
$num3 = array(1, 10);

$newArray1 = array_merge($num1, $num2, $num3);

 $newArray1 becomes (100, 111, 120, 100, 3, 5, 1, 10) .

Example 2:

$names1 = array(5 => "Peter", 24 => "Aaron");
$names2 = array(5 => "Zac", 4 => "Alfred", 7 => "Avi");
$newArray2 = array_merge($names1, $names2);

Keys are renumbered in the merged array if any of the arrays passed to the array_merge() function is an associative array with integer keys.

In the example above, $newArray2 becomes (0 => "Peter", 1 => "Aaron", 2 => "Zac", 3 => "Alfred", 4 => "Avi") .

The key for "Peter" is renumbered from 5 to 0 . The same applies to all the other keys.

Example 3:

$str1 = array('A'=> 12, 'B' => 5, 'C' => 8);
$str2 = array('A' => 15, 'D' => 10);
$newArray3 = array_merge($str1, $str2);

If two or more array elements have the same string keys, the last one overrides the earlier ones.

In the example above, $newArray3 becomes ('A'=> 15, 'B' => 5, 'C' => 8, 'D' => 10) .

 'A'=> 12 is replaced by 'A'=> 15 .

We’ve covered some of the commonly used array functions in PHP. For a complete list of all the built-in array functions, check outhttps://www.php.net/manual/en/ref.array.php.

Pages: 1 2 3 4 5 6 7 8 9 10 11 12 13