7 Sept 2013

The Top 5 Most Used PHP features

learn-php-development-design
learn-php-development

1. Usort

usort allows the developer to sort an array based on a compare function that's configurable by the developer. This allows you to create more complex sorting algorithms that are not provided by the standard core array sort functions.
The callback/closure function has two parameters, which are two items in the array you have asked to sort on. It's then for you to decide if the first argument is greater, smaller or equal to the second argument. This is done by returning an integer value. Anything smaller than zero will assume the first argument is smaller than the second. Zero means the arguments are equal. Greater than zero means the first argument is larger than the second.
One great application for usort that we tend to use on a daily basis is to sort a simple multi-dimensional array. For example, let's say we have an array of students that consists of an associative array of name and age. By using the usort function along with acallback/closure function, we are able to pick the age and sort by ascending or descending.
For example, the code below is sorting by the age variable for each student in the students array. The callback/closure function provides the algorithm that compares the two ages and decides if the first age is greater than the second.

  1. $successful = usort($students, function  ($a, $b) {
  2.     return $a['age'] - $b['age'];
  3. });

2. Hashing API

There was an issue not too long ago with big-name sites getting hacked and insecure hashed passwords getting stolen. Back in the day, using the MD5 function was sufficient to hash a password, so it was secure. The problem with MD5 and SHA1 is that they are fast to perform the hashing algorithm. Along with the invention of faster processors and the utilisation of GPUs, people have the ability to process many hundreds of thousands of hashes per second, even on a standard desktop computer or laptop.
The new hashing API introduced in PHP5.5 provides an easy-to-use layer on top of bcrypt to create secure (for now) hashes that are a lot harder to solve by hackers. The example below shows how any string variable can be hashed. A salt will be created automatically and the hashing routing will have a cost of 15. The cost will make the hashing more secure but slower to complete.
  1. $hash = password_hash($password, PASSWORD_BCRYPT, ['cost' => 20]);

3. SimpleXML Class

When we have to deal with XML files we tend to use the SimpleXML class. This easy-to-use class gives you the ability to read and edit XML files via objects. Using these objects gives you the ability to return values and iterate over arrays in the usual ways, as well as a set of simple methods to modify the XML’s structure. If you just need to grab something specific in the XML then using the built-in method of XPath, you can return a set of SimpleXML Element objects for just the path that you provided.
As well as reading XML, SimpleXML also provides the methods to create new documents and/or inject elements back into the imported XML. This can then be saved all in a few lines of code.
The SimpleXML class is provided as a standard extension for PHP. Although it’s not in the core of PHP, it is enabled by default.
The example below shows a very simple example to get a list of public photos from Flickr and display the content html of each photo.
  1. /* Load flickr Public Feed */
  2. $xml = simplexml_load_file('http://api.flickr.com/services/feeds/photos_public.gne');
  3. if(is_object($xml)){
  4.     /* Get each entry and echo the content tag */
  5.     foreach($xml->entry as $photo) echo $photo->content;
  6. }

4. glob

The glob function provides an easy one-line solution for creating an array of path names using a pattern you provide. glob may not be as fast as using the opendir and readdir combination, but if you just want to iterate over a directory, or you’re searching for a specific file type such as an image, then using glob could be a good solution to your problem.
The first argument is a glob pattern string that's similar to a regular expression in the way that it functions, but the syntax to create the pattern has some differences. This allows you to search for a varied subset of files and folders that are contained in a directory.
One big disadvantage of using glob is that all the results are stored into memory in one go. If you have a very large folder full of files you can soon run out of memory, and in this instance, it would be better to use opendir and readdir as it creates a read stream buffer.
Using the example below we are able to return all the image files in the $imagePath directory. An array will be returned to the $images variable.
  1. /* Find all image files in image folder */
  2. $images = glob($imagePath.'*.{gif,jpeg,jpg,png}',GLOB_BRACE);

5. array_map

The standard core functions that PHP provide tend to perform faster, than creating your own similar functions using PHP code. A great example of this is utilising array_map instead of creating a for or which loop. array_map allows you to create a function called a callback that will be applied to every item in an array you supply.
For example, if you had an array of lowercase letters, a callback function can be created to uppercase all the characters in the array. On a small-sized array, the speed increase would be quite small, but once you start using larger arrays, you can really see a significant difference in speed.
In the example below we are converting the alphabet from lowercase to uppercase. We have provided the array_map function with a string of the name of the function we want to process. In this case we are using strtoupper to convert each letter in the array.

If there’s a need for more complex functionality, we can also provide the array_map function, a closure like in the usort example above.
  1. $alphabet=array();
  2. /* Create lower Case Alphabet */
  3. for($i=97;$i<123;$i++) $alphabet[]=chr($i);
  4. /* Convert to Uppercase */
  5. $upperCaseAlphabet = array_map('strtoupper',$alphabet);

No comments:

Post a Comment