Skip to content


Forgotten PHP : Some useful and simple PHP features that I often forget about.

I’ve been programming with PHP for many years but regardless how familiar I am with the language I am constantly looking at reference documentation for reminders on how to do things. Here’s a list of some really handy PHP functions that I often forget about and then will stumble across them in documentation and am reminded why I shouldn’t forget about them.

How to format text to be inserted into a url

If you need to pass some text or a dynamic string in a URL use urlencode() and urldecode()

// encoding the string
$str = "Jerry's Bedding Plants & Ice Cream";
$url = 'http://www.example.com/page.php?args=' . urlencode( $str );

// decoding the string in page.php
$str = urldecode( $_GET['args'] );

Parsing a query string

Want to automatically take the query string and dump the values into an array ? Use parse_str() . You can easily get the query string from $_SERVER['QUERY_STRING']

$query = $_SERVER['QUERY_STRING'];  // foo=bar&bar=foo&cool=me&you=ok
$vars = array();
parse_str( $query, $vars );
print_r( $vars );

/* output
Array
(
  [foo] => bar
  [bar] => foo
  [cool] => me
  [you] => ok
)
*/

Creating a formatted string

Most people are very familiar with printf() in php but if you’re like me you often forget about sprintf() which returns your formatted string instead of printing it to the screen.

$isodate = sprintf("%04d-%02d-%02d", $year, $month, $day);

Another one you might forget about is vsprintf() which is similar to sprintf() but works with an array

$data = array( $year, $month, $day );
$isodate = vsprintf("%04d-%02d-%02d", $data );

Formatting numbers

For some reason I always forget the arguments for the PHP number_format() function. The function takes one, two or 4 arguments ( will not accept just 3 arguments ).

// string number_format  ( float $number  , int $decimals  , string $dec_point  , string $thousands_sep  )
$number = number_format( '32456.82', 2, '.', ',' );

Count the number of times a small string occurs in a large string

// how many times do I say rad;
$str = "I've got some rad moves, super rad moves, I've got rad mad bad not sad rad moves.";
$rad_count = substr_count( $str, 'rad' );

Happy coding nerds !

Posted in Code, PHP.

Tagged with , , , , , , , .


0 Responses

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.



Some HTML is OK

or, reply to this post via trackback.



close