I have an array
$hourly = array(
"01" => "0",
"02" => "0",
"03" => "0",
"04" => "0",
"05" => "0",
"06" => "0",
"07" => "0",
"08" => "0",
"09" => "0",
"10" => "0",
"11" => "0",
"12" => "0",
"13" => "0",
"14" => "0",
"15" => "0",
"16" => "0",
"17" => "0",
"18" => "0",
"19" => "0",
"20" => "0",
"21" => "0",
"22" => "0",
"23" => "0"
);
And I have a bunch of data like "01" and "03" and "21" and I want to add (+1) to that specific value in the array. So with the data set "01","03","21","01","22" the resulting array would be
$hourly = array(
"01" => "2",
"02" => "0",
"03" => "1",
"04" => "0",
"05" => "0",
"06" => "0",
"07" => "0",
"08" => "0",
"09" => "0",
"10" => "0",
"11" => "0",
"12" => "0",
"13" => "0",
"14" => "0",
"15" => "0",
"16" => "0",
"17" => "0",
"18" => "0",
"19" => "0",
"20" => "0",
"21" => "1",
"22" => "1",
"23" => "0"
);
How could I go about doing that? Is there a function to add 1 to an array element?
Given an array which represents a number, add 1 to the array. Suppose an array contain elements [1, 2, 3, 4] then the array represents decimal number 1234 and hence adding 1 to this would result 1235. So new array will be [1, 2, 3, 5].
Approach: To add one to the number represented by digits, follow the below steps : Parse the given array from the end as we do in school addition. If the last elements are 9, make it 0 and carry = 1. For the next iteration check carry and if it adds to 10, do the same as step 2.
In short, array[i - i] gives you the value of the element at the index 1 less than i.
Normally, you'd be able to do:
$array["key"]++;
However, your arrays have a few peculiarities you should fix;
None of these make your script not work, but the inconsistency and unnecessary performance hit are avoidable.
$updates = array("01","03","21","01","22");
foreach($updates as $num) {
$hourly[$num]++;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With