Beyond popular array functions in php [with examples]
Coding (Php 7.x)
Make you work easy mastering some extra array functions
It was a hot night several years ago when taking the school notes of the previous morning,
I found out I have been assigned a very interesting homework.
The test that the computer science's professor wanted me and my mates to do was to take a sentence of our choice (with at least a dozen words) and turn it into an array with the words itself instead of the elements.
Then make a copy of the array and create a new variable consisting of a string containing the words taken from the newly created array.
Finally, by writing a condition statement, verify that the two strings were the same and send a success or error message according to the result.
I still remember that after the first couple of hours experimenting with multiple variables creation, foreach cycles here and there and whatever else, I pulled the notepad on the wall and went to sleep.
Level of frustration: 100/100;
Keep in mind that I was still a student and the PHP language was a new thing for me.
The next day the same professor showed me that, to complete the exercise, it would have been enough to use functions already built-in inside the language and 3 lines would have been enough instead of the 600 that I was using.
This has changed my career forever, and I'm sure once you understand this, it will change yours too.
The principle here is: DO NOT REINVENT THE WHEEL
During the last few weeks, we have seen that there are different categories of functions that PHP provides in order to work profitably with arrays and elements present within them.
If you are new here or have not followed the series carefully, this series has been divided into several parts,
in the first part, we saw what arrays are and how to best exploit them using the built-in functions within PHP, in the second chapter all the most popular features have been linked,
Then we saw how to filter the elements of array (which is one of the main functions used by the web developer) and finally how to sort array's elements themselves.
In this chapter, you will see some extra features, some secrets and tips that you can decide to use right away.
Most of these features are very easy to understand, others you will find as you continue your career in web development in PHP framework and core packages.
The functions you will learn today
explode()
This was the first function the professor taught me that day.
There is absolutely no need to do multiple loops or use complex solutions in order to derive an array from a string.
PHP provides this built-in function in its core and has been implemented to do this.
The explode() function has 3 parameters.
The first two mandatory ones, the third one is not mandatory and if I have to be frank, not even much used.
The first parameter is the delimiter, as mentioned above in our case it will be composed of spaces,
The second parameter is the string itself, nothing to say here.
The third parameter is a bit more complex and consists of the limit.
The limit can be positive, negative or zero.
If negative all components are returned except for the last one.
If the limit indicated is 0, the limit considered will be one element.
A positive limit instead returns an array containing a maximum number of elements equal to the specified number.
Now,
What do we need when we want to create different elements from a string?
It's easy!
we need the string and the elements that make it up.
Let's take a look at this example:
"Hi Ho Hi Ho It's Off To Work We Go"
This is the string, the elements that we need and that must be inserted inside the array are the words.
The simplest way to insert single words is through the use of delimiters, in this case, the spaces that separate the words
The result of this function will be an array with 10 elements.
Let's analyze how this string is structured:
Here is an example that uses the third parameter:
$str = "Hi Ho Hi Ho Its Off To Work We Go"; // With no limit print_r(explode('', $str)); // With limit print_r(explode('', $str, 2)); Array ( [0] => Hi [1] => Ho [2] => Hi [3] => Ho [4] => Its [5] => Off [6] => To [7] => Work [8] => We [9] => Go ) Array ( [0] => Hi [1] => Ho Hi Ho Its Off To Work We Go )
There are several factors that you need to consider when applying the explode() function:
If the delimiter is composed of an empty string the function will return the value FALSE, if the delimiter is not present in the string and the limit indicated is negative the returned value will be an empty string.
You can find some other example of the explode function on W3schools
implode()
In the previous paragraph, you saw how to get an array from a string,
As you've already deduced, PHP allows you to do the opposite operation as well.
By supplying an array to the implode() function you will get a string containing the values of the array elements,
Nothing could be simpler.
There are some peculiarities to note,
Being a function that was initially published in PHP 4, it is not surprising that after all these years and different versions of the language the function has changed from what it was originally.
Let's take a deeper look:
implode() has two attributes:
The first is officially called glue and consists of a string containing the set of characters or words that will separate the different elements of the array.
More unique than rare, even being the first parameter of the function, it is not a mandatory field,
It can, in fact, be omitted, and replaced by the second parameter of this function.
The second parameter of the function is the array,
It will eventually be transformed into the string.
Do you want to know a particularity,
The array is not a mandatory field either.
How is it possible?
PHP allows you to invoke this function without specifying any parameters, the result will provide an empty string variable.
It may seem like a positive factor but as there is no mistake, you have to pay even more attention to the result obtained by the function
Here is an example:
$dwarfs = ['Doc', 'Grumpy', 'Happy', 'Sleepy', 'Dopey', 'Bashful', 'Sneezy']; $string = implode(",", $dwarfs); echo $string; // Doc, Grumpy, Happy, Sleepy, Dopey, Bashful, Sneezy
array_sum()
This function is a shortcut to a specific use that you can make of elements within the array.
Suppose you have an array containing several numbers and you want to make the sum between them.
The most logical reasoning would be to create a loop and sum the elements within a variable.
array_sum() performs exactly this operation, automatically and in a single line.
It works with both numerical and associative arrays.
The values that this function considers are integers or floats while the returned value is a numeric type value which can be 0 (if the array is empty) or the total sum of the elements.
$numbers = array( "first" => 11.4, "second" => 4.1, "third" => 8.9 ); echo array_sum($numbers); // 24.4
It can also be used to derive the average value of an array of numbers.
Copy and paste this line below:
$average_of_numbers = array_sum($numbers) / count($numbers); // 8.13
array_product()
Incredibly similar to array_sum()
Both the syntax and the conditions are the same as those indicated in the previous chapter.
The only difference between the two functions is that the final result of array_product() is the product of all the numbers present between the elements.
$numbers = array(2, 4, 6, 8); echo array_product($numbers); // 384
Curiosity: if the array selected as a parameter is an empty array, contrary to what you might think the value derives is not 0 or NULL but number 1.
Here is a demonstration below.
echo array_product([]); // 1
array_column()
This function returns the values present in a column of an associative array supplied as a parameter,
array_column() comes from version 5.5 of PHP and uses 3 parameters, of which the first 2 are mandatory.
The first parameter is the array from which we want to get the values,
The second parameter consists of the name of the key of the array.
Normally the returned array is numeric but, indicating another of the other columns present within the selected array, the returned array will be of an associative type and will have the values of the third field as a key.
Given all the moving parts used by this function, it is not difficult to understand that its use can result in several errors,
In fact,
it is a rather complex function and I advise you to always be attentive to the result provided and that there are no errors or warnings.
$dwarfs = array( array( 'id' => 1, 'name' => 'Doc', 'voice' => 'Roy Atwell' ), array( 'id' => 2, 'name' => 'Grumpy', 'voice' => 'Pinto Colvig' ), array( 'id' => 3, 'name' => 'Happy', 'voice' => 'Otis Harlan' ), array( 'id' => 4, 'name' => 'Sleepy', 'voice' => 'Pinto Colvig' ), array( 'id' => 5, 'name' => 'Dopey', 'voice' => 'Eddie Collins' ), array( 'id' => 6, 'name' => 'Bashful', 'voice' => 'Scotty Mattraw' ), array( 'id' => 7, 'name' => 'Sneezy', 'voice' => 'Billy Gilbert' ) ); print_r(array_column($dwarfs, 'name', 'id')); Array ( 1 => Doc 2 => Grumpy 3 => Happy 4 => Sleepy 5 => Dopey 6 => Bashful 7 => Sneezy )
compact()
If you have ever used any of the PHP frameworks, surely you have already come across this function.
If you have never used a PHP framework or want to have a look at what's available in the market.
compact() is widely used in order to create unique variables that can be sent to views in applications that use the MVC paradigm.
Some PHP frameworks have even modified this function to make it more suitable for their needs,
Laravel uses the with() function for example
As said this function creates a single variable of type array containing all the variables and the values inserted as parameters.
compact() examines the code and searches for all variables with the given name.
Here is a concrete example:
$name = "Doc"; $voice = "Roy Atwell"; $movie = "Snow White and the Seven Dwarfs"; print_r(compact("movie", "empty_variable", array("name", "voice"))); Array ( [movie] => Snow White and the Seven Dwarfs [name] => Doc [voice] => Roy Atwell )
extract()
Let's do some computer science:
In computer science, a symbol table is a data structure used by a linguistic translator, in the case of PHP an interpreter.
An interpreted language is a type of programming language.
The majority of its implementations execute instructions directly,
There is no need to previously compiling the code into machine-language instructions.
I explain more about it in the PHP Basic for experts series
Each identifier called symbol in a program's source code is associated with information about its declaration.
The symbol table stores information about the symbol.
The extract() function imports the variables in the current symbol table from an array.
In simple words, it produces exactly the opposite result of compact().
It has 3 parameters, 2 of which are not mandatory.
The first parameter is the array, it must be of an associative type.
The second parameter consists of one of the available flags, it indicates how the keys are treated in the case of invalid inputs.
There are several flags available:
EXTR_OVERWRITE
In the event of a collision, the function overwrites the existing variable.
If no key is indicated, this flag will be the default value.
EXTR_SKIP
In the event of a collision, the function does not overwrite the existing variable.
EXTR_PREFIX_SAME
If there is a collision, enter prefix as the prefix of the variable name.
EXTR_PREFIX_ALL
It prefixes all variable names with a prefix.
EXTR_PREFIX_INVALID
It prefixes only the names of invalid or numeric variables with the prefix.
EXTR_IF_EXISTS
It overwrites the variable only if it already exists in the current symbol table otherwise it will not perform any operation.
EXTR_PREFIX_IF_EXISTS
Create variable names with a prefix only if the non-fixed version of the same variable is already present in the current symbol table.
EXTR_REFS
Extracts the variables as references. This means the variable values refer to the values of the array parameters.
You can use this flag alone or combine it with any other flag (use OR in this case).
You can have a more detailed view of these flags by using the official PHP manual
The third parameter, also optional, is a string type variable and consists of the prefix with which the created variables will be named.
As with some of the functions already seen in this article, the array is taken as a reference, which translates into two meanings.
The first is that the array itself is modified, not a variable returned from the array.
The second is the variable returned by the function is of another type in this case of the integer type and indicates the number of variables imported in the symbol table.
In a sense, this function works closely with the PHP interpreter.
Which means we need to pay more attention to the values to be used.
$name = "Doc"; $dwarf = array( "movie" => "Snow White and the Seven Dwarfs", "name" => "Happy", "voice" => "Roy Atwell" ); extract($dwarf, EXTR_PREFIX_SAME, "pre"); echo "$movie, $name, $voice, $pre_name"; // Snow White and the Seven Dwarfs, Doc, Roy Atwell, Happy
A phrase emphasized several times by both experienced developers and the manual itself is that you don't have to use extract() with an untrusted date as global variables like $ _GET or $ _FILES
Conclusion of the series
As for other series in my blog (head here to browse among them) once again we have reached the end of another path.
In this series we have seen MORE THAT 50 FUNCTIONS that involve more or less directly arrays and its elements, we have gone from the basic functions to specific sectors such as ordering and filtering of elements.
Although some PHP frameworks now use collections instead of arrays, knowing how they work and how to best use them will not only make you understand deeper into the heart of this programming language but make you a better programmer, and this is invaluable at any stage of your career.
This series has come to an end,
This does not mean you need to finish learning!
Quite the opposite,
There is plenty of information out there and platforms that have been created just with the purpose to make you a better programmer and learn new skills.
In my opinion, one of the best platform, and one from which I have learned a lot from is teamtreehouse.com.
They have classes, video, and quizzes on PHP, Python, creation of API and how to start your own business as well if you are a freelancer.
Today for you there are also 4 Months Off on their Basic Annual Plan
CLICK HERE AND TAKE ADVANTAGE OF THE OFFER NOW
My last advice is to go back to this post and the others in this series several times over the next few months (add it to your browser's bookmark to make things easier) and review the features you find most interesting.
Once you deeply understand how they work you will see that it will be much easier to apply them to the everyday code.