Check if a PHP function exists

Josh Sherman
1 min read
Software Development PHP

Let’s use json_encode as an example here. Prior to PHP 5.2.0 JSON support was only available via a PECL extension and since 5.2.0 it’s been available as part of the PHP core. You could check that the server is running PHP 5.2.0 or above, but that could result in a false positive because the server could be running 5.0 and have the aforementioned PECL extension installed. A better solution is to check that the function exists via the function_exists() function:

if (function_exists('json_encode'))
{
	$json = json_encode($value);
}
else
{
	throw new Exception('The function json_encode() is not available.');
}

The function_exists() function can be used to check for the existence of both internal PHP functions as well as user defined functions. Not included would be checking if a class function exists (I’ll save that for another post ;).

Join the Conversation

Good stuff? Want more?

Weekly emails about technology, development, and sometimes sauerkraut.

100% Fresh, Grade A Content, Never Spam.

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Head of Engineering and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.

Currently Reading

Parasie Eve

Previous Reads

Buy Me a Coffee Become a Sponsor

Related Articles