Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

array_search() not finding 0th element [duplicate]

Tags:

arrays

php

I have a large array of stock ticker symbols, as I am for a project writing a stock market simulation webapp. One of my helper functions is one to determine whether the entered stock is valid by checking the array for the symbol. To do this, I am using array_search(). The problem I have is one by checking edge cases. It seems that the search isn't picking up the 0th element, even though it picks up other elements completely fine. Here is part of the array:

[0] => AAC
[1] => AACC
[2] => AACOU
[3] => AACOW
[4] => AAIT
[5] => AAME
[6] => AAON
[7] => AAPL
[8] => AAWW
[9] => AAXJ
[10] => ABAX
[11] => ABCB
[12] => ABCD
[13] => ABCO
[14] => ABFS
[15] => ABIO
[16] => ABMD
[17] => ABTL
[18] => ABVA
[19] => ACAD
[20] => ACAS
[21] => ACAT
[22] => ACCL

Etc, etc. As said before, it works fine for other elements, just not the 0th one. It returns FALSE when searching for AAC.

Here is the PHP code I am using.

<?php   
                if(isset($_GET[stock])) {
                    $ticker = $_GET[stock];
                    $ticker = trim($ticker);
                    print("<pre>Ticker is $ticker</pre>");

                    print("Validity: " .        Stock::isValidStock($ticker));

                    print('<pre>');
                    $stock = Stock::getStockList();
                    print_r($stock);
                    print((bool)array_search('AAC', $stock));
                    print('</pre></br>');
                }
            ?>

Here is the test web page I'm using. You can change the stock by editing the query string in the url. As I said, ?stock=AAC returns false, while something like ?stock=GOOG is true. Thanks for any help!

like image 277
Saxophlutist Avatar asked Oct 13 '12 06:10

Saxophlutist


1 Answers

array_search() returns the key of the first match if one is found. When said key is 0 and you cast it into a bool, it will become false.

What you want to do is compare it to false using the not identical operator === :

//if you don't need the index you can skip assigning it to a variable
$index = array_search('AAC', $stock); 

if ($index !== false) 
{
    // found!
}
like image 108
NullUserException Avatar answered Sep 18 '22 20:09

NullUserException