HowTo: PHP Compare Two Text Strings

by on January 6, 2011 · 0 comments· LAST UPDATED November 6, 2012

in

How can I compare two strings using php? How do I use php to compare two strings?

Tutorial details
DifficultyEasy (rss)
Root privilegesNo
RequirementsPHP or LAMP
Estimated completion timeN/A

PHP is an HTML-embedded scripting language. It is an open source project. PHP also offers built-in database integration for several commercial and non-commercial database management systems, so writing a database-enabled webpage with PHP is fairly simple.

By default PHP is installed on Unix like operating system. The syntax is as follows to compare two strings using php:

 
<?php
$string1 = "Foo";
$string2 = "Bar";
if ( $string1 == $string2 ){
  echo "Equal: Yes\n";
}
else{
  echo "Equal: No\n";
}
?>
 

PHP version 4 and 5 comes with a new function called strcmp(). It is a binary safe string comparison function. The syntax is:

 
int strcmp ($string1, $string2);
 

The function returns the following values:

  1. Returns < 0 if string1 is less than string2.
  2. Returns > 0 if string1 is greater than string2.
  3. Returns 0 if they are equal.

Example

 
<?php
$string1 = "Foo";
$string2 = "Bar";
if ( strcmp ( $string1, $string2) == 0  ){
  echo "Equal: Yes\n";
}
else{
  echo "Equal: No\n";
}
?>
 

Another simple example:

 
 $type=$what;
 $catoutput="NULL";
 foreach( $cats as $key=>$values ){
  $mycat=$values[0];
  $myimg=$values[1];
  $mydesc=$values[2];
  if ( $key == $type ) {
    $catoutput = 'Plan: '. $mycat;
    $catoutput .= 'Image: ' . $myimg;
    $catoutput .= 'Description: ' . $mydesc;
    return $catoutput;
  }
}
 
TwitterFacebookGoogle+PDF versionFound an error/typo on this page? Help us!

{ 0 comments… add one now }

Leave a Comment

Tagged as: , ,

Previous Faq:

Next Faq: