1

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;

        }
    }
web.learner
  • 101
  • 2
  • 8
  • 3
    You can't have array `$values` with same key `a` used 3 times and therefore there is no condition on this script where `array_key_exists()` should return `true`. – Havenard Jul 29 '18 at 06:02
  • 1
    You need to change the the array to what you actually have. We can't answer the question if we don't know what your array looks like. Preferably post the real array with var_export or json_encode. There may be faster methods that looping if we only get to see the real array. – Andreas Jul 29 '18 at 06:11
  • OMG I'm so dumb !!! I need to stop coding overtime. Thank you @Havenard – web.learner Jul 29 '18 at 06:12

2 Answers2

2

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, e.g.:

$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;
    // ...
kmoser
  • 8,780
  • 3
  • 24
  • 40
0

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

Kunal
  • 219
  • 2
  • 9