简体   繁体   中英

array_key_exists not working as expected

Problem

I'm having trouble using the PHP function array_key_exists . Even though my array has the key, the function always returns false. I wonder if there is a issue regards using a dynamically growing array. I'm new to PHP, sorry if the question is annoying trivial.

Expected behavior

I need the array_key_exists function returning true if the array has the key.

What I tried to solve

I tried to use isset(CounterArray[$key]) instead but I got no success.

I've already read the PHP docs, for the specific function and I've also checked similar questions on stack-overflow but none of them were suitable for my case. I'm shamefully expending a huge time with this.

code

$values=[
        "a"=>100,
        "a"=>100,
        "a"=>100,
        "b"=>200,   
    ];


    $counterArray = array();

    foreach ($values as $key => $price) {

        if(!array_key_exists( $key , $counterArray))){
            $counterArray[$key]=$price;

        }else{

            $counterArray[$key] += $price;

        }
    }

Your $values array contains duplicates of the same key 'a' , which will be ignored. Thus, $counter_array will end up containing an exact copy of $values .

It sounds like $values should be an array of arrays, eg:

$values = [
    ["a"=>100],
    ["a"=>100],
    ["a"=>100],
    ["b"=>200],
];

Of course, your loop will have to change accordingly:

foreach ($values as $a) {
    list( $key, $price ) = $a;
    // ...

It's because your actual array is internally like array(2) { ["a"]=> int(100) ["b"]=> int(200) You will get above output when you do var_dump($values); In your code

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM