array_search returning wrong value

Marcelo Camargo

I'm implementing manually the array_unique function. I'm doing this:

class Prelude {
    public static function unique($xs) {
        $arr = array();
        foreach($xs as $atom) {
            if (!array_search($atom, $arr)) {
                var_dump($arr); 
                echo "<br>";
                array_push($arr, $atom);
            }
        }
        return $arr;
    }
}

Prelude :: unique(array(1, 1, 1, 1, 1, 3, 3, 4, 4, 4, 6, 7, 8));

I noticed that it works very well, except when $atom is 1. In my foreach loop, when I check if the value is already contained in the array and the value I want to check is one, it simply ignores and says me that there is no 1 in my array. Here is my output:

http://ideone.com/HpWtIl

And here is when I check if there is 1 in [1, 1, 1]:

http://ideone.com/eF3gcS

Can somebody explain me this?

Lucas Freitas

Simple, Marcelo.

You're checking with ! which is the non-strict checking. You must check for !== FALSE. 1 is TRUE.

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

분류에서Dev

strlen returning wrong value

분류에서Dev

array_search() function not search the value inside the array

분류에서Dev

function returning wrong value while executing

분류에서Dev

Returning the wrong value in basic Java program

분류에서Dev

PHP Array_search won't find an existing value

분류에서Dev

Access SQL Query Returning Wrong Value for Count Field

분류에서Dev

DateTimes deserializing wrong: JsonConvert is returning wrong dates

분류에서Dev

Search and replace hash value. What am I doing wrong?

분류에서Dev

json_decode is returning a null value instead of an array

분류에서Dev

PHP function not returning value

분류에서Dev

Returning Value from Actor

분류에서Dev

AngularJS : service not returning value

분류에서Dev

ArrayList returning null value

분류에서Dev

Returning a value from a Method

분류에서Dev

Returning a value from a Thread?

분류에서Dev

Capistrano returning wrong release_path

분류에서Dev

If date > curDate returning wrong result, WHY?

분류에서Dev

PHP strtotime returning the wrong result on calculation

분류에서Dev

Wrong value calculated by Delphi

분류에서Dev

Why is diff returning an incorrect value?

분류에서Dev

Returning a value from a recursive function

분류에서Dev

numpy not returning the correct median value

분류에서Dev

Conditional SUM not returning any value

분류에서Dev

Functions keeps returning the same value

분류에서Dev

Function not returning the Value of its Key

분류에서Dev

Is checking if a variable is equal to a value and then returning that value redundant?

분류에서Dev

JCrop resizes selection to wrong value

분류에서Dev

"Select count()" returns wrong value

분류에서Dev

Pandas on Apply passing wrong value