Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing two identical strings returns false in PHP

Tags:

php

cakephp

I'm trying to compare two strings. When I echo them, they appear to be identical, yet when I compare them with the '==' operator, it returns false. For example, when running the code below on my database. It outputs things like "APPARENTLY Apple does not equal Apple". What is the reason?

if ($this->data['list_text']) { // The user has entered into textarea

    $list = nl2br($this->data['list_text']);

    $list_array = explode('<br />', $list);

    $ranking = 1;
    $company_array = $this->CompanyList->CompanyRanking->Company->find('list', null);

    // This is the comparison bit
    foreach ($list_array as $key => $value) {
        $companyId = null;
        foreach ($company_array as $key2 => $value2) {
            if ($value2 != $value) {
                echo 'APPARENTLY ' . $value2 . ' does not equal ' . $value;
            } else {
                $companyId = $key2;
                break;
            }
        }

        $this->data['CompanyRanking'][$ranking]['ranking'] = $ranking;
        $this->data['CompanyRanking'][$ranking]['company_id'] = $companyId;
        $ranking++;
    }
}
like image 438
gomezuk Avatar asked Oct 14 '09 11:10

gomezuk


People also ask

Can you use == to compare strings in PHP?

The most common way you will see of comparing two strings is simply by using the == operator if the two strings are equal to each other then it returns true. This code will return that the strings match, but what if the strings were not in the same case it will not match.

How can we compare two strings in PHP?

The strcmp() function compares two strings. Note: The strcmp() function is binary-safe and case-sensitive. Tip: This function is similar to the strncmp() function, with the difference that you can specify the number of characters from each string to be used in the comparison with strncmp().

How do you compare two strings with the same?

The equals() method compares two strings, and returns true if the strings are equal, and false if not. Tip: Use the compareTo() method to compare two strings lexicographically.

Can we compare two strings directly?

In order to compare two strings, we can use String's strcmp() function. The strcmp() function is a C library function used to compare two strings in a lexicographical manner. The function returns 0 if both the strings are equal or the same. The input string has to be a char array of C-style string.


1 Answers

Try var_dump() instead of echo.

echo 'APPARENTLY '.$value2.' does not equal '.$value;   
echo '<pre>Debug: ';
echo 'value='; var_dump($value);
echo 'value2='; var_dump($value2);
echo '</pre>';

It provides additional information. E.g. the actual type. And the length of strings.

like image 62
VolkerK Avatar answered Sep 20 '22 11:09

VolkerK