5 Helpful PHP Features You Might Not Know About

Even after using a language for years, we might come across some features or functions which are new to us. In this article, I have compiled 5 helpful features in PHP you might not have heard about.

1. Counting Words in a String

How many times you might have to count the words in a string? You might have written a sophisticated solution for solving this trivial problem. Exploding the string using PHP explode() and then counting the elements in the resulting array is one solution.

However, you can do it in a single statement using str_word_count. This function takes in a single string parameter and returns the count of words in the string as shown below:

<?php
	$str = "Count the number of words in this string.";
	echo str_word_count($str); //Outputs 8
?>

2. Printing All Defined Variables

You can print all the variables defined in a string using get_defined_vars() function. This function takes no parameters and returns a multidimensional array containing all the defined variables in its scope. This unutilized but yet helpful feature comes very useful while debugging.

<?php

	$var1 = 10;
	$var2 = 'Concatly';
	$var3 = array('PHP', 'Functions', 'Explained');
	print_r(get_defined_vars());
?>

//Output:

Array
(
    [_GET] => Array
        (
        )

    [_POST] => Array
        (
        )

    [_COOKIE] => Array
        (
        )

    [_FILES] => Array
        (
        )

    [var1] => 10
    [var2] => Concatly
    [var3] => Array
        (
            [0] => PHP
            [1] => Functions
            [2] => Explained
        )

)

3. Register Shutdown Function

Register shutdown function lets you run some code just before the script ends. Imagine that you need to print the total time taken by a script for some benchmark analysis.

<?php
	$startTime = microtime(true);

	/*
		Some complex logic here
	*/

	$endTime = microtime(true);
	echo 'Total time taken: '.($endTime - $startTime);
?>

This may seem trivial as you just have to add some code at the end of your script. However, if the script fails in between or there is a fatal error, then your last piece of code won’t run. Also, if you put exit() in between then also the script will stop running and your code will not run.

If you register a function in register_shutdown_function then it will be always called no matter why your script ended. This is very handy if you need to log any termination or for your own statistics.

<?php
	register_shutdown_function('handler_function');
	$startTime = microtime(true);

	/*
		Some complex logic here
	*/

	function handler_function() {
		global $startTime;
		$endTime = microtime(true);
		echo 'Time taken: '.($endTime - $startTime);
	}
?>

In the above example, the handler_function will be automatically called just before the script ends. To demonstrate that it works even if you exit() the script in between, consider the given example. Notice that even putting a die after the first echo statement, the handler function is still executed.

<?php
	register_shutdown_function('handler_function');

	echo 'Before Dying'.PHP_EOL;
	die;
	echo 'After Dying'.PHP_EOL;

	function handler_function() {
		echo 'Script Ended';
	}

	/*
	Output:

	Before Dying
	Script Ended

	*/
?>

4. Storing Complex Objects As Strings

Have you ever felt the need of storing a complex variable in a text file or sending it to a friend on chat? You don’t need to convert your variables to strings using sophisticated methods. Simply use PHP serialize() and unserialize() function as follows:

<?php
	
	$tempArray = array(
		'name' => 'John Doe',
		'contact' => array(
			'email' => '[email protected]',
			'phone' => '000000000'
		)
	);
	//Convert a complex array to a string
	$stringConverted = serialize($tempArray);

	echo $stringConverted;
	/*
	a:2:{s:4:"name";s:8:"John Doe";s:7:"contact";a:2:{s:5:"email";s:18:"[email protected]";s:5:"phone";s:9:"000000000";}}
	*/

	//Convert that string back to array
	$newVarArray = unserialize($stringConverted);

	print_r($newVarArray);
	/*
		Array
		(
		    [name] => John Doe
		    [contact] => Array
		        (
		            [email] => [email protected]
		            [phone] => 000000000
		        )

		)
	*/


?>

Alternatively, you can also convert your objects to JSON values using json_encode(). JSON is more widely used and accepted in other languages and applications. Moreover, JSON takes in less storage than native serialized string because it is more compact.

<?php
	
	$tempArray = array(
		'name' => 'John Doe',
		'contact' => array(
			'email' => '[email protected]',
			'phone' => '000000000'
		)
	);
	//Convert a complex array to a json string
	$stringConverted = json_encode($tempArray);

	echo $stringConverted;
	/*
	{"name":"John Doe","contact":{"email":"[email protected]","phone":"000000000"}}
	*/

	//Convert that string back to array
	$newVarArray = json_decode($stringConverted, true);

	print_r($newVarArray);
	/*
		Array
		(
		    [name] => John Doe
		    [contact] => Array
		        (
		            [email] => [email protected]
		            [phone] => 000000000
		        )

		)
	*/


?>

5. String Compression

It is possible to compress strings in PHP to use less storage without involving any data loss using gzenencode() function.

<?php
	$string =
	"Lorem ipsum dolor sit amet, consectetur
	adipiscing elit. Nunc ut elit id mi ultricies
	adipiscing. Nulla facilisi. Praesent pulvinar,
	sapien vel n mi metus, at lacinia
	augue. Sed magna nisi, ornare in mollis in, mollis
	sed nunc. Etiam at justo in leo congue mollis.
	Nullam in neque eget metus hendrerit scelerisque
	eu non enim. Ut malesuada lacus eu nulla bibendum
	id euismod urna sodales. ";
	 
	$compressed = gzencode($string);
	 
	echo "Original size: ". strlen($string)."\n";
	/* 
		Original size: 397
	*/
	 
	 
	 
	echo "Compressed size: ". strlen($compressed)."\n";
	/* 
		Compressed size: 261
	*/
	 
	// Retrieve original string
	$original = gzdecode($compressed);

	echo "Retrieved size: ". strlen($original);
	/*
		Retrieved size: 397
	*/

?>

Alternatively, you can also use gzcompress()  and gzuncompress()  which can achieve similar results using a different compression algorithm.

Conclusion

In this post you learnt about 5 helpful PHP features that were maybe unknown to you earlier. Hopefully, you found this post helpful.

You can read about more PHP on Concatly. Kindly give your suggestions in the comments to help me improve my articles.

Spread the Knowledge
Categories:

Leave a Reply

Your email address will not be published. Required fields are marked *