How can one differentiate between an array and an object in PHP?
In PHP, one can differentiate between an array and an object by using the `is_array()` and `is_object()` functions. `is_array()` returns true if the variable is an array, while `is_object()` returns true if the variable is an object. This can be useful when working with different data types and needing to determine how to handle them in your code.
$data = [1, 2, 3]; // array
$person = new stdClass(); // object
if (is_array($data)) {
echo "Data is an array";
} elseif (is_object($data)) {
echo "Data is an object";
}
if (is_array($person)) {
echo "Person is an array";
} elseif (is_object($person)) {
echo "Person is an object";
}
Keywords
Related Questions
- In PHP, what are the advantages and disadvantages of using sessions to store variables from an external source compared to extracting them directly from a URL query string?
- What are the best practices for handling form data in PHP to ensure proper functionality and security?
- How can the use of constants in PHP functions lead to errors in PHP 8.1?