In php, we can check if a function exists with the php function_exists() function.

if (function_exists('max')) {
    echo "max() exists!";
} else {
   echo "max() doesn't exist!";
}

if (function_exists('other_function')) {
    echo "other_function() exists!";
} else {
   echo "other_function() doesn't exist!";
}

//Output:
max() exists!
other_function() doesn't exist!

When working in php, it is useful to be able to check if a function exists or not.

To check if a function exists in our php program, we can use the function_exists() function. function_exists() takes a function name in the form of a string and checks to see if the function exists.

If the function exists, function_exists return true. Otherwise, function_exists returns false.

function_exists() can be useful so that we don’t try to call a function which hasn’t been defined and get an error.

Below are some examples of testing to see if a function exists in php.

if (function_exists('max')) {
    echo "max() exists!";
} else {
   echo "max() doesn't exist!";
}

if (function_exists('other_function')) {
    echo "other_function() exists!";
} else {
   echo "other_function() doesn't exist!";
}

//Output:
max() exists!
other_function() doesn't exist!

How to Check if a User Defined Function Exists in php with function_exists()

We can use the function_exists() function to check if a user defined function exists in our php code.

Below are some examples of checking for the existence of user defined functions in php with function_exists().

function exampleFunction($a) {
    return "What's up?";
}

if (function_exists('exampleFunction')) {
    echo "exampleFunction() exists!";
} else {
    echo "exampleFunction() doesn't exist!";
    function anotherFunction() {
        return "Not much.";
    }
}

if (function_exists('anotherFunction')) {
    echo "anotherFunction() exists!";
} else {
    echo "anotherFunction() doesn't exist!";
}

// Output:
exampleFunction() exists!
anotherFunction() doesn't exist!

Hopefully this article has been useful for you to learn how to check if a function exists or not in php.

Categorized in:

PHP,

Last Update: February 26, 2024