Reputation: 101
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.
I need the array_key_exists
function returning true if the array has the key.
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.
$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;
}
}
Upvotes: 1
Views: 1354
Reputation: 229
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
Upvotes: 0
Reputation: 9273
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;
// ...
Upvotes: 2