Define an index on a new array in a loop? - php

I have the following code:
$chart_data = array();
foreach ($range as $range_day) {
foreach ($numbers as $number) {
if($range_day == $number['date']){
#$chart_data[$range_day] += $number['events'];
} else {
if(isset($chart_data[$range_day])){
$chart_data[$range_day] += 0;
}
}
}
}
This line: $chart_data[$range_day] += 0; was giving me an undefined index error, so I added the isset check, but it's not set so it wrecks my array. I know that it's not set, and I don't care, but I read all over that the # solution is in poor taste. How can I remove the error the correct way?

You could just set it to zero at the beginning:
$chart_data = array();
foreach ($range as $range_day) {
$chart_data[$range_day] = 0;
foreach ($numbers as $number) {
if($range_day == $number['date']){
$chart_data[$range_day] += $number['events'];
} else {
if(isset($chart_data[$range_day])){
$chart_data[$range_day] += 0;
}
}
}
}

Did you take a look at the array_key_exists function: http://php.net/manual/en/function.array-key-exists.php ?
Something like:
$chart_data = array();
foreach ($range as $range_day) {
foreach ($numbers as $number) {
if(!array_key_exists($range_day, $array)) {
$chart_data[$range_day] = 0;
}
if($range_day == $number['date']){
$chart_data[$range_day] += $number['events'];
}
}
}

You can check if it's not set, then set it:
foreach ($numbers as $number) {
if (!isset($chart_data[$range_day])) {
$chart_data[$range_day] = 0;
}
if ($range_day == $number['date']) {
$chart_data[$range_day] += $number['events'];
} else {
$chart_data[$range_day] += 0; // you're just adding 0 so why have this line at all?
}
}
This answers assumes that there is the possibility that $range could contain a duplicate $range_day and so it won't overwrite the corresponding element in $chart_data.

Related

Find first duplicate in an array

Given an array a that contains only numbers in the range from 1 to a.length, find the first duplicate number for which the second occurrence has the minimal index. In other words, if there are more than 1 duplicated numbers, return the number for which the second occurrence has a smaller index than the second occurrence of the other number does. If there are no such elements, return -1.
My code:
function firstDuplicate($a) {
$unique = array_unique($a);
foreach ($a as $key => $val) {
if ($unique[$key] !== $val){
return $key;
}else{
return -1;
}
}
}
The code above will be OK when the input is [2, 4, 3, 5, 1] but if the input is [2, 1, 3, 5, 3, 2] the output is wrong. The second duplicate occurrence has a smaller index. The expected output should be 3.
How can I fix my code to output the correct result?
$arr = array(2,1,3,5,3,2);
function firstDuplicate($a) {
$res = -1;
for ($i = count($a); $i >= 1; --$i) {
for ($j = 0; $j < $i; ++$j) {
if ($a[$j] === $a[$i]) {
$res = $a[$j];
}
}
}
return $res;
}
var_dump(firstDuplicate($arr));
By traversing the array backwards, you will overwrite any previous duplicates with the new, lower-indexed one.
Note: this returns the value (not index), unless no duplicate is found. In that case, it returns -1.
// Return index of first found duplicate value in array
function firstDuplicate($a) {
$c_array = array_count_values($a);
foreach($c_array as $value=>$times)
{
if($times>1)
{
return array_search($value, $array);
}
}
return -1;
}
array_count_values() will count the duplicate values in the array for you then you just iterate over that until you find the first result with more then 1 and search for the first key in the original array matching that value.
Python3 Solution:
def firstDuplicate(a):
mySet = set()
for i in range(len(a)):
if a[i] in mySet:
return a[i]
else:
mySet.add(a[i])
return -1
function firstDuplicate($a) {
foreach($a as $index => $value) {
$detector[] = $value;
$counter = 0;
foreach($detector as $item) {
if($item == $value) {
$counter++;
if($counter >= 2) {
return $value;
break;
}
}
}
}
return -1;
}
It's easy to just get the first number that will be checked as duplicated, but unfortunately, this function exceeded 4 seconds with a large array of data, so please using it with a small scale of array data.
EDIT
I have new own code fixes execution time for large array data
function firstDuplicate($a) {
$b = [];
$counts = array_count_values($a);
foreach($counts as $num => $duplication) {
if($duplication > 1) {
$b[] = $num;
}
}
foreach($a as $value) {
if(in_array($value, $b)) {
$detector[] = $value;
$counter = 0;
foreach($detector as $item) {
if($item == $value) {
$counter++;
if($counter >= 2) {
return $value;
break;
}
}
}
}
}
return -1;
}
The new code target the current numbers having a reputation only by using array_count_values()
function firstDuplicate($a) {
$indexNumber = -1;
for($i = count($a); $i >= 1 ; --$i){
for($k = 0; $k < $i; $k++){
if(isset($a[$i]) && ($a[$i] === $a[$k]) ){
$indexNumber = $a[$k];
}
}
}
return $indexNumber;
}
Remove error from undefined index array.

Find unique (not repeating) combination php

I'm facing a technical problem here, I have an array [PER_DAY, PER_SIZE, PER_TYPE], I want to find combination all of the item without repeating the element, the result should be
[PER_DAY]
[PER_SIZE]
[PER_TYPE]
[PER_DAY, PER_SIZE]
[PER_DAY, PER_TYPE]
[PER_SIZE, PER_TYPE]
[PER_DAY, PER_SIZE, PER_TYPE]
This code repeating same value, so the result is too much.
$arr = ['PER_DAY', 'PER_SIZE', 'PER_TYPE'];
$result = [];
function combinations($arr, $level, &$result, $curr=[]) {
for($i = 0; $i < count($arr); $i++) {
$new = array_merge($curr, array($arr[$i]));
if($level == 1) {
sort($new);
if (!in_array($new, $result)) {
$result[] = $new;
}
} else {
combinations($arr, $level - 1, $result, $new);
}
}
}
for ($i = 0; $i<count($arr); $i++) {
combinations($arr, $i+1, $result);
}
This question possible duplicate, but I cannot found example similar like this, thanks.
function pc_array_power_set($array) {
// initialize by adding the empty set
$results = array(array( ));
foreach ($array as $element)
foreach ($results as $combination)
array_push($results, array_merge(array($element), $combination));
return array_filter($results);
}
$set = ['PER_DAY', 'PER_SIZE', 'PER_TYPE'];
$power_set = pc_array_power_set($set);
echo '<pre>';
print_r($power_set);
You have make combination from array, will help you :-PHP array combinations

How to reiterate same loop again in php?

I have the following foreach loop, how can I reiterate over the same loop index again?
$n = 0;
$currentTotal = 0;
$currentSettlement = $coupons[0]->settlement_id;
foreach ($coupons as $coupon){
if($currentSettlement == $coupon->settlement_id){
$currentTotal += $coupon->amount;
}else{
$settlements[$n]['total'] = $currentTotal;
$currentTotal = 0;
$currentSettlement = $coupon->settlement_id;
$n++;
// after this I want to reiterate current loop from the beginning
}
}
If you want necessary foreach loop you can use a function which you fix that it runs only twice:
$n = 0;
$currentTotal = 0;
$currentSettlement = $coupons[0]->settlement_id;
for2loop(1,$coupons);
function for2loop($loopagain,$coupons)
{
foreach ($coupons as $coupon) {
if ($currentSettlement == $coupon->settlement_id) {
$currentTotal += $coupon->amount;
} else {
$settlements[$n]['total'] = $currentTotal;
$currentTotal = 0;
$currentSettlement = $coupon->settlement_id;
$n++;
if($loopagain == 1)
for2loop(2,$coupons); // after this I want to reiterate current loop from the beginning
}
}
return $currentSettlement
}
but i think that yu must prefer while loop or for loop better

Last 3 values using foreach loop in php

I have a foreach loop. There has uncountable value. I want to print last 3 values.
foreach($arr as $key=>$value) {
//print last 3 value.
}
Try this:
$i = 0;
foreach($arr as $key=>$value) {
if (count($arr) - $i < 4)
print($value);
$i++;
}
Try this you can use like this
$i = 0;
$len = count($array);
foreach ($array as $item) {
if ($i == 0) {
// first
} else if ($i == $len - 3) {
// last
}
else if ($i == $len - 2) {
// last
}
else if ($i == $len - 1) {
// last
}
// …
$i++;
}

Getting an undefined offset in my PHP array while in a foreach

I need some help, even though I think I'm checking for the length of the array and I should be breaking out of the loop, I still get warnings on my [else if ($value....] line. So either I'm missing something crucial or I've been staring at this code segment too long and its obvious. Any insight would be appreciated.
$count = count($filter); //Filter is an array
if ($count > 1 ){
//Compare values and generate a range to choose from
$i = 1;
foreach($filter as $value){
//Break the loop if at the end of the array
if ($i >= $count){
//throw new exception($i .' '.$count);
break;
}
//if the value is smaller then the next procceding value, because they are already in order of presidence,
//add it to our range of potentials.
else if($value < $filter[$i]->value){
array_push($range, key($filter));
}
$i++;
}
}else {
return false;
}
I suspect that there are gaps in your array. Try this:
$filter = array_values($filter); // this will remove any gaps in the array
$count = count($filter);
if ($count <= 1)
return false;
for ($i = 0; $i < $count; $i++)
{
if ($i != $count-1 && $filter[$i]->value < $filter[$i+1]->value)
array_push($range, key($filter));
}
Your array might have non-numeric keys. Then try this:
foreach($filter as $key=>$value)
{
// test for $filter[$key];
}
Or your $filter array doesn't hold objects, then you can't use the -> in
$filter[$key]->value
try this code.... no need of checking count..
$range = array();
$i = 1;
foreach($filter as $value)
{
if(isset($filter[$i]) && $value < $filter[$i]->value)
{
array_push($range, key($filter));
$i++;
}
else
{
break;
}
}

Categories