HowTo: PHP Compare Two Text Strings

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

Tutorial details
Difficulty level Easy
Root privileges No
Requirements PHP or LAMP
Est. reading time N/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:

$string1 = "Foo";
$string2 = "Bar";
if ( $string1 == $string2 ){
  echo "Equal: Yes\n";
  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
  2. Returns > 0 if string1 is greater than string2.
  3. Returns 0 if they are equal.


$string1 = "Foo";
$string2 = "Bar";
if ( strcmp ( $string1, $string2) == 0  ){
  echo "Equal: Yes\n";
  echo "Equal: No\n";

Another simple example:

 foreach( $cats as $key=>$values ){
  if ( $key == $type ) {
    $catoutput = 'Plan: '. $mycat;
    $catoutput .= 'Image: ' . $myimg;
    $catoutput .= 'Description: ' . $mydesc;
    return $catoutput;

🐧 Get the latest tutorials on Linux, Open Source & DevOps via RSS feed or Weekly email newsletter.

🐧 0 comments... add one

CategoryList of Unix and Linux commands
Disk space analyzersdf duf ncdu pydf
File Managementcat cp mkdir tree
FirewallAlpine Awall CentOS 8 OpenSUSE RHEL 8 Ubuntu 16.04 Ubuntu 18.04 Ubuntu 20.04
Modern utilitiesbat exa
Network UtilitiesNetHogs dig host ip nmap
OpenVPNCentOS 7 CentOS 8 Debian 10 Debian 8/9 Ubuntu 18.04 Ubuntu 20.04
Package Managerapk apt
Processes Managementbg chroot cron disown fg glances gtop jobs killall kill pidof pstree pwdx time vtop
Searchingag grep whereis which
User Informationgroups id lastcomm last lid/libuser-lid logname members users whoami who w
WireGuard VPNAlpine CentOS 8 Debian 10 Firewall Ubuntu 20.04
0 comments… add one

Leave a Reply

Your email address will not be published.

Use HTML <pre>...</pre> for code samples. Still have questions? Post it on our forum