PHP Exercise : Different datatype comparison in PHP
Write a program to compare between things that are not integers.
Suppose the strings are -
$str1 = "00004";
$str2 = "008";
$str3 = "00007-STR";
Solution
The comparison operators work for strings as well as numbers. PHP has automatic type conversions that can lead to counter intuitive results when the strings are interpretable as numbers. If you compare a number with a string or the comparison involves numerical strings, then each string is converted to a number and the comparison performed numerically.
In the given example, we have taken three stings and perform comparison between them using comparison operator -
<?php
$str1 = "00004";
$str2 = "008";
$str3 = "00007-STR";
if($str2 < $str1) {
echo "$str1 is less than $str2<br/>";
}
if($str3 < $str2) {
echo "$str3 is less than $str2<br/>";
}
if($str1 < $str3) {
echo "$str1 is less than $str3<br/>";
}
?>
Output of the above code
00007-STR is less than 00800004 is less than 00007-STR
Related PHP Programs for Practice
PHP - Division table programPHP - Prime Number Program
PHP - Print numbers 10 to 1 using recursion
PHP - Loop through an associative array
PHP - Differentiate between fgets, fgetss and fgetcsv
PHP - Set session on login
PHP - Convert text to speech
PHP - Copying or moving a file
PHP - Locking a file
PHP - CURL Cookie Jar
PHP - Password Hashing
PHP - Emoji Unicode Characters
PHP - Age calculator
PHP - Get array key
PHP - Capitalize first letter
PHP - Set Timezone
PHP - Remove duplicates from array
PHP - Calculate percentage of total
PHP - Fibonacci Series Program
PHP - Lock a file
PHP - Insert image in database