Some Useful PHP functions and features

Some useful but lesser known PHP functions

In this article I am going to cover up some lesser known but Useful PHP Functions which offers some great functionalities. Not all but many of these are usually re coded. Here’s the list of such Useful PHP Functions and features that I have compiled over time. These might also come in handy for you in your day to day coding.

  1. Converting Newline to Break – nltobr
  2. Placeholder replacement – strtr
  3. Die
  4. Parsing Url – parse_url
  5. glob
  6. Magic Constants
  7. str_word_count()
  8. Serialization – json_encode & json_decode

Converting Newline to Break – nltobr

Most people are not known to this small yet useful PHP function, I too tried to re-create the function few months ago. This function places the HTML <br/> tag before the line break character “\n” within a string.

Uses: This function come in handy when you are displaying some user’s input coming from a textarea. This help maintain the line breaks user puts within the textarea

Placeholder replacement – strtr

Ok here’s another very useful php function which is often underused. Let’s see an example what can be done using this function.

<?php

$content = "Hi #user, 
Thanks for registering. Your username is #username.
";

$trans = array("#user" => "ABC", "#username"=> "XYZ");

echo strtr($content, $trans);

?>

You can use it to replace substrings within a string

Uses:

I think this can be used in many scenarios, Here are few I use it for

  1. For creating email templates with placeholder for dynamic values – This allow me to save my email templates within database or in single config file
  2. Use it for translation
  3. Use in in place of string concatenations when I have to deal with long strings for cleaner code.

Die

I have seen people doing below

echo "something";
exit;

Instead of

die('something');

Saves you one line 🙂

URL Parsing – parse_url()

This small function comes in handly when you are dealing with a URL. Instead of doing string operations on the url you can use that function to get different parts of the URL into array.

Usage:

<?php

$url = 'http://username:password@hostname/path?arg=value#anchor';

print_r(parse_url($url));

echo parse_url($url, PHP_URL_PATH);
?>
#OUTPUT
Array
(
    [scheme] => http
    [host] => hostname
    [user] => username
    [pass] => password
    [path] => /path
    [query] => arg=value
    [fragment] => anchor
)

Glob

Are you still using opendir() to loop through folders in PHP? Doesn’t that require a lot of repetitive code everytime you want to search a folder? Luckily, PHP’s glob() is a much smarter solution.

# WITHOUT GLOB -----------
$dir = "/etc/php5/";

// Open a known directory, and proceed to read its contents
if (is_dir($dir)) 
{

	if ($dh = opendir($dir)) 
	{

		while (($file = readdir($dh)) !== false) 
		{
			echo "filename: $file : filetype: " . filetype($dir . $file) . "\n";
		}

		closedir($dh);

	}

}

#Using GLOB -----------
$dir = "/etc/php5/*";

// Open a known directory, and proceed to read its contents
foreach(glob($dir) as $file) 
{
	echo "filename: $file : filetype: " . filetype($file) . "
";
}

Magic Constants

Strange name right! But they seems perfectly named. They are Constants but can have different value based on the context they are being used.

There are eight magical constants that change depending on where they are used. For example, the value of __LINE__ depends on the line that it’s used on in your script. These special constants are case-insensitive and are as follows:

__LINE__ The current line number of the file.
__FILE__ The full path and filename of the file. If used inside an include, the name of the included file is returned. Since PHP 4.0.2, __FILE__ always contains an absolute path with symlinks resolved whereas in older versions it contained relative path under some circumstances.
__DIR__ The directory of the file. If used inside an include, the directory of the included file is returned. This is equivalent to dirname(__FILE__). This directory name does not have a trailing slash unless it is the root directory. (Added in PHP 5.3.0.)
__FUNCTION__ The function name. (Added in PHP 4.3.0) As of PHP 5 this constant returns the function name as it was declared (case-sensitive). In PHP 4 its value is always lowercased.
__CLASS__ The class name. (Added in PHP 4.3.0) As of PHP 5 this constant returns the class name as it was declared (case-sensitive). In PHP 4 its value is always lowercased. The class name includes the namespace it was declared in (e.g. Foo\Bar). Note that as of PHP 5.4 __CLASS__ works also in traits. When used in a trait method, __CLASS__ is the name of the class the trait is used in.
__TRAIT__ The trait name. (Added in PHP 5.4.0) As of PHP 5.4 this constant returns the trait as it was declared (case-sensitive). The trait name includes the namespace it was declared in (e.g. Foo\Bar).
__METHOD__ The class method name. (Added in PHP 5.0.0) The method name is returned as it was declared (case-sensitive).
__NAMESPACE__ The name of the current namespace (case-sensitive). This constant is defined in compile-time (Added in PHP 5.3.0).

String Word Count – str_word_count()
Have you ever done below?


$string = 'this is a string';
$wordArray = explode(' ', $string);

if(count($wordArray) > SOMENUMBER){
 //do something
}

I did it many time when I started php. But we already have a short little function to do it.


$string = 'this is a string';
if(str_word_count($string) > SOMENUMBER){
 //do something
}

That’s it for now. Did I missed something? Please tell me in comment and I’ll more then happy to include that in the list. Keep Coding.

Serialization – json_encode/json_decode & serialize/unserialize

Well not really lesser known but still including these functions.

Serialization is mainly used when you need to store (either in database or file) or transfer complex types i.e objects and arrays. There are actually two ways to do the same

  1. First one is to use serialize() and unserialize() function
  2. Second to use json_encode() and json_decode() function

both are very useful functions but I have preferred to use the JSON approach for arrays and serialize approach for objects. I like the fact about JSON that this is more readable and portable then serialize strings but then there are some drawbacks too. Do your research properly before you choose one.

http://stackoverflow.com/questions/804045/preferred-method-to-store-php-arrays-json-encode-vs-serialize

The following two tabs change content below.

Ankit Kumar

Team Leader at Logiciel Solutions
This is my personal blog. I post about Laravel, Angular, SQL and Web Technologies here. I have been into web development for 7 years and learning new things always interest me. Looking forward to find a teacher in you all.