PHP Lessons - Lesson 11 - Functions for Working with Strings and Arrays
We already know different data types and some functions for working with them. In fact, PHP has a huge number of built-in functions — so many that a full review would take more than one textbook. So let's focus on a few essential ones. We'll start with how to convert an array into a string, and then back from a string into an array.
PHP: From Array to String — implode()
Let’s look at an example:
<?php $colors = array(1 => 'yellow', 2 => 'red', 3 => 'blue'); // define the array $string = implode(',', $colors); // convert the array to a string print $string; // output the string ?>
The result will be all colors printed as a single string, separated by commas. In the implode()
function, the first parameter defines the delimiter used between array elements, and the second parameter is the array itself. Simple and clean. Now let’s do the opposite — convert a string into an array.
PHP: From String to Array — explode()
Another quick example:
<?php $colors = array(1 => 'yellow', 2 => 'red', 3 => 'blue'); // define the array $string = implode(',', $colors); // convert the array to a string $string .= ',black,white'; // append more colors $newArray = explode(',', $string); // convert the string back into an array print_r($newArray); // print the resulting array ?>
The result is an array with all colors, including the ones we appended. Note: the explode()
function assigns numeric keys starting from 0. So the fifth element will have key 4. The first parameter in explode()
is the delimiter used to separate elements in the string, and the second parameter is the string itself.
PHP: String Length & Array Length
Sometimes we need to count the length of a string or the number of elements in an array. Sure, this is easy if the string is short — but if the string has 200–300 characters or the array contains 500 items, we need a better way. That’s where built-in PHP functions come in handy:
$colors = array(1 => 'yellow', 2 => 'red', 3 => 'blue'); $string = implode(',', $colors); $string .= ',black,white'; $newArray = explode(',', $string); print strlen($string); // output the length of the string
Using the strlen()
function, we get the string length — easy and convenient. For example, mine returned 35.
Now let’s count the number of elements in the array:
$colors = array(1 => 'yellow', 2 => 'red', 3 => 'blue'); $string = implode(',', $colors); $string .= ',black,white'; $newArray = explode(',', $string); print count($newArray); // count the elements in the array
The result is 5 — again, very simple and useful. In the near future, I’ll compile a list of all PHP functions for working with strings and arrays. But for now, these examples should give you a good idea of how PHP functions work.