Is_Array Vs. Is_String in PHP

The is_array and is_string functions are two of PHP's built-in Boolean functions. You use each in data validation, checking a piece of information to determine its type. PHP is a weakly typed scripting language that does not require explicit type declaration of variables. This sometimes makes it difficult to know what values exist in variables, and these two functions can help you determine the data types.

  1. Syntax

    • To use either function, you need only type the function name followed by the variable to evaluate, enclosed in brackets with a semi-colon at the end of the line. For example, type "is_string($myvar);" to check and see if the $myvar variable contains a string. You can use these functions in an if statement to determine the flow of control based on the return value, or use them with the echo function to print the results to the screen.

    Input Types

    • Both the is_string and is_input functions take exactly one parameter as input. If you try to use either no parameters or more than two parameters, PHP returns a warning, stating that only one argument is expected. In most cases, you will pass PHP variables to the function to determine their data types. You can pass a string literal to either function, but in these cases, you know the result without actually having to do the validation.

    Return Values

    • As Boolean functions, these functions are similar to each other in that they can only return one of two possible values: "true" or "false." However, they don't return the same value based on the input criteria. The is_string function returns "true" when the input type is a string and "false" otherwise, while the is_array function returns "true" when the input type has an array structure and "false" if it does not.

    Considerations

    • To create a string, you need to enclose the value in quotation marks. To create an array, you need to build it using PHP's "array" data structure. An array can hold values of any type. An array of strings returns "true" in the is_array functions. Passing an array of strings to the is_string function returns "false." However, if you pass one element of an array that has a string value, the is_string function returns "true." Both functions cannot return "true" based on the same input, but both may return "false."

Related Searches:

References

Comments

Related Ads

Featured