Note 010 Notes on == comparison operator in PHP

黄舟
Release: 2023-03-04 09:06:01
Original
1097 people have browsed it

Recently, when performing comparison operations, I encountered some problems, details that I usually ignore. However, I didn’t expect that the problem would arise this time.

The == comparison operator in PHP means: when the values ​​of the two data are equal, it returns true, otherwise it returns false. Note that what is said here is that when the values ​​​​are equivalent, the result is true. That is to say, the types of values ​​​​are not compared here. For example: 12 == '12' The result will be true.

Due to the weak type of PHP variables, many times the type of the variable is not deliberately considered, and the problem this time is caused by the variable type.

My problem occurs when using the array_search function. The function of

array_search is to search a data with a given value. If the value exists, the index corresponding to the value is returned. If this value occurs multiple times, the first retrieved index is returned. If the value does not exist, return false.

My problem occurs in an environment similar to the following:

<?php$testA = array(   
 &#39;a&#39; => &#39;123&#39;,   
  &#39;b&#39; => &#39;iphp8.com&#39;,   
   &#39;c&#39; => &#39;014778&#39;,   
   &#39;d&#39; => &#39;14778&#39;,
);
   echo array_search(&#39;14778&#39;, $testA);
Copy after login

The result obtained at this time will be c.

By default, array_search does not compare the types of values, that is, == comparisons are made. When it comes to pure numbers, even strings seem to be converted into numbers for comparison, so it doesn't matter how many leading 0s there are, "14778" and "014778" are equal, so in the above example, the returned The result is c, not d as we thought.

At this time, in order to get the result we want, we need to perform === comparison, which requires comparing both values ​​and types.

For array_search, we can perform congruent comparison by giving its third parameter a true value.

The above is the content of note 010 == comparison operator in PHP. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template