Wednesday, March 11, 2020

Use Is_String to Check if a Variable Is a String in PHP

Use Is_String to Check if a Variable Is a String in PHP The is_string() PHP function is used to check if a type of variable is a  string. A string is a data type, such as floating point or integer, but it represents text rather than numbers. A string uses a set of characters that includes spaces and numbers. For instance, an address such as 1234 Broadway and the sentence I ate 3 hotdogs contain numbers that should be treated as text, not as numbers. How to Use the Function Is_string is used within an if () statement to treat strings in one way and non-strings in another. It returns true or false. For example: ?php if (is_string(23)) {echo Yes;} else {echo No;}? The code above should output No because 23 is not a string. Lets try this again: ?php if (is_string(Hello World)) {echo Yes;} else {echo No;}? Since Hello World is a string, this would echo Yes. Specifying a String A string can be specified in four ways: Single quotedDouble quoted  Heredoc syntaxNowdoc Syntax Each of these methods requires strict adherence  to PHP rules, which are available at the PHP website. The simplest method, single-quoted strings, requires special treatment when literal single quotation marks or literal backslashes appear in the string. Include a backslash in front of the single quotation mark or backslash within the string. The example below illustrates this treatment: ?php//  Outputs:  Arnold said:  Ill  be  backecho  Arnold said:  I\ll  be  back;//  Outputs:  I  deleted  C:\*.*?echo  I  deleted  C:\\*.*?;? Similar Functions is_float() – determines if the type of variable is floatis_int() – determines if the type of variable is integeris_bool() – determines if a variable is a booleanis_object() – determines if a variable is an objectis_array() – determines if a variable is an array