is_resource()
The is_resource() function is a built-in function in PHP that checks whether a variable is a resource or not. A resource is a special variable that holds a
Introduction
The is_resource() function is a built-in function in PHP that checks whether a variable is a resource or not. A resource is a special variable that holds a reference to an external resource, such as a database connection or a file handle.
Syntax
The syntax of the is_resource() function is as follows:
The PHP syntax of the is_resource()
bool is_resource(mixed $var)The function takes a single parameter, $var, which is the variable to be checked for being a resource. The function returns true if the variable is a resource, and false otherwise.
Example Usage
Here is an example of how to use the is_resource() function in PHP:
Example of PHP is_resource()
<?php
$handle = fopen("file.txt", "r");
$var = "hello";
echo is_resource($handle) . "\n"; // output: 1 (true)
echo is_resource($var) . "\n"; // output: (false)
fclose($handle);
?>In this example, we open a file file.txt and create a file handle $handle. We then define a variable $var that is a string. We use the is_resource() function to check whether each variable is a resource. The output shows that $handle is a resource (true), while $var is not a resource (false).
Conclusion
The is_resource() function is a useful tool for checking whether a variable is a resource in PHP. It can be used to ensure that a variable has the expected data type before performing operations on it, or to handle resources and non-resources in a particular way. By using this function, developers can ensure that their code is working with the correct data types and avoid errors that may occur when working with mixed data types.
Practice
What is the functionality of the is_resource() function in PHP?