Array_push and array_search

Hi,

I have defined the function [tt]array_push_assoc [/tt]below so I can use the [tt]array_push [/tt]with custom keys (in my case strings representing formatted dates):

[php]
function array_push_assoc($array, $key, $value)
{
$array[(string)$key] = (int)$value;
return $array;
}
[/php]

I am using happily (without generating error in my code) and inserted in it one element. The [tt]var_dump [/tt] of my array created with [tt]array_push_assoc [/tt] and named [tt]$balance_updates [/tt] is included below:

[tt]
array(1) { [“2016-03-02”]=> int(34800) }
[/tt]

Now my problem comes when I use [tt]array_search [/tt] as follows:

[php]
array_search(“2016-03-02”,$balance_updates)
[/php]

This produces an empty string.

Is the problem in my function, or am I missing something very obvious?

Thank you for your help.

array_search (PHP 4 >= 4.0.5, PHP 5, PHP 7)

array_search — Searches the array for a given value and returns the corresponding key if successful

http://php.net/manual/en/function.array-search.php

You’re searching for a key, not a value. You can just address the key directly though

[php]if (!isset($balance_updates[‘2016-03-02’])) {
// something
}[/php]

[php]$result = isset($balance_updates[‘2016-03-02’]) ? $balance_updates[‘2016-03-02’] : null;

// $result is int value if exists or null if it doesn’t exist.[/php]

Sponsor our Newsletter | Privacy Policy | Terms of Service