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, e.g.:Of course, your loop will have to change accordingly: