PHP Variables – Check if a variable is a string

In this post we will be creating PHP script that will check if an existing variable is a string, to do this we will be using the ‘is_string()’ function. For this example our variables will be stored in an array and we will carry out a check on each item within.

See our array of items for this example below.

$array = array(26.132, "10.243", null, "Aloha", "", 192, true);

In the snippet of PHP code below we are iterating the above array and using the ‘is_string()’ function to check if an item is a string. The True or False values will be printed beside the item and each item will be printed on a new line.

<?php
$array = array(26.132, "10.243", null, "Aloha", "", 192, true);

foreach ($array as $item) {
    echo $item . " - " ;
	echo var_dump(is_string($item)) . "<br>";
}

?>

The above would return the following as output.

26.132 - bool(false)
10.243 - bool(true)
- bool(false)
Aloha - bool(true)
- bool(true)
192 - bool(false)
1 - bool(false)

Take a look at some of our other content around the Python programming language by clicking here.

Leave a Reply