Weblincs.co.uk is proud to...
As a part of our ongoing que...
WebLincs.co.uk is proud to a...
In this sequence of articles I aim to inform you of some practical optimisation examples. This will hopefully make your PHP applications run a little faster when dealing with large datasets.
Searching arrays in PHP is a somewhat common operation and usually means using the in_array() function – used to traverse the givin array by means of iteration. This can be quite a slot process when walking through large arrays of data. A simple way of doing this, knowing the key or indexof the array, is to see if the variable isset() at that particular point in the structure. An example of this can be seen below:
$my_array = array(“banana”, “apple”, “cherry”); if(in_array(“cherry”, $my_array)) { echo(“Cherry is in the array”); }
Our optimisation approach would lead to the following:
$my_array = array(“banana” => 1, “apple” => 1, “cherry” => 1); if(isset($my_array['cherry'])) { echo(“Cherry is in the array”); }
Working with strings is a necessary, yet intensive task. Strings are in their construct, a basic array of characters. Most of the common methods of string comparators and manipulation techniques require that you iterate through the string, locating or modifying the character(s) in question. A Much more simple approach is to utilise the PHP accessor (as an operator override) to access individual characters in the array by the means of array syntax (e.g. array[0]). Please see below for an example:
$my_string = "The cat sat on the mat."; if(strlen($my_string) > 10) { echo("This string is too long."); }
Optimising this procedure would look like:
$my_string = "The cat sat on the mat."; if(isset($my_string{10})) { echo("This string is too long."); }
Back to Web Development Articles.