Some of Unknown and rarely used but very helpful functions of PHP
- Date: Jan 13, 2010
- Author: Rakshit Patel
- Comments: 14
- Tags: __autoload() function, Compress strings using gzcompress(), Dynamically include files, eliminate empty elements using preg_split(), Execute require at run time, Helpful functions, Helpful tips, Important PHP Functions, Magic Functions, Magic Tricks, PHP Inbuilt functions, PHP Programming tips, preg_split function, Store IP address as integers, Uncompress string using gzuncompress(), validate real time email address using checkdnsrr()
- Categories: Helpful Tips and Tricks, PHP Programming
Today i have searched google and php manual to find out some of useful inbuilt functions which are not general use but having some great functionality. I found some of the function which developers rarely use but these are the very useful functions. You must spend some time to read this functions and i am sure that this functions help you while developing an application.
1. Swapping two values using list() function
$x = 1;
$y = 2;
list($x, $y) = array($y, $x);
echo $x; // Outputs – 2
echo $y; // Outputs – 1
2. Compress/Uncompress strings
You can compress long strings using gzcompress() and than make an entry in to database. This will save a space and make your database lighter at some level. You can uncompress the compressed string by using gzuncompress() function.
3. Validate real time email address
What we are validating for email address is not a perfect validation. If anyone enter firstname.lastname@example.org than this is not a valid email address. You can validate real time email by the checkdnsrr() function. It checks the email's host address if it's a valid DNS record.
3. highlight_file() function
Output HTML string with nice colored using above function. Many servers are configured to automatically highlight files with a phps extension. To use this , you have to enable phps by adding this line to the httpd.conf:
AddType application/x-httpd-php-source .phps
4. Easy manage of IP addresses as strings.
IP address can be stored as integers using the ip2long(). If you want to convert it back to IP address from integer string than use long2ip() function.
Some of the advantages to store IP address as Integers are :
1) Less memory space used
2) Searching of IP address will be faster
3) Easy to check if IP address is inbetween IP address ranges
5. __autoload() method – PHP5
The magic method __autoload() function is a convenience that allows you to include files dynamically when instant of class is created.
This function will search file name as class name and add that file at run time. This will reduce a load time because files will be included as per needs.
6. preg_split function
This function will split string to array of strings. This can also be done using the explode function. Benifits of using preg_split function is , it will eliminate empty strings.