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++;
}
}
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.
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().
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With