pee2pee
pee2pee

Reputation: 3792

PHP - array_search not working as expected - works then fails

So I have the following:

    echo array_search('Resolved at Tier 1', array_column($getHighLevelOverviewPeriodsArray, 'status'));
    print_r($getHighLevelOverviewPeriodsArray);

    if (!array_search('Resolved at Tier 1', array_column($getHighLevelOverviewPeriodsArray, 'status'))) {
        $resolved = array('status' => 'Resolved at Tier 1', 'amount' => 0);
        array_splice($getHighLevelOverviewPeriodsArray, 0, 0, array($resolved));
    }
    print_r($getHighLevelOverviewPeriodsArray);

The echo spits out a zero which is right. It does exist in the first place. However the second part runs (if statement) and the array_splice gets executed. The output of print_r is below.

What is it being executed even though it's there?

I have the exact same code for Tier 2, character for character (expect for the 2) and that works as expected.

Array
(
    [0] => Array
        (
            [status] => Resolved at Tier 1
            [amount] => 10
        )

    [1] => Array
        (
            [status] => Resolved at Tier 2
            [amount] => 7
        )

    [2] => Array
        (
            [status] => Resolved Total
            [amount] => 17
        )

    [3] => Array
        (
            [status] => Phone Calls
            [amount] => 0
        )

)
Array
(
    [0] => Array
        (
            [status] => Resolved at Tier 1
            [amount] => 0
        )

    [1] => Array
        (
            [status] => Resolved at Tier 1
            [amount] => 10
        )

    [2] => Array
        (
            [status] => Resolved at Tier 2
            [amount] => 7
        )

    [3] => Array
        (
            [status] => Resolved Total
            [amount] => 17
        )

    [4] => Array
        (
            [status] => Phone Calls
            [amount] => 0
        )

)

Upvotes: 2

Views: 58

Answers (1)

jh1711
jh1711

Reputation: 2328

Read the warning in the manual http://php.net/manual/en/function.array-search.php. 0 == false after type juggling. You need:

 if (false !== array_search ...

instead of:

 if (!array_search...

edit to add: Tier 2 works as expected, because indexes greater than zero are 'truthy'.

Upvotes: 1

Related Questions