mohamed tebry mohamed tebry - 7 days ago 6
PHP Question

do while loop not working well php

I am trying to push values after they are being calculated to different arrays
as you can see the

min($arrival)
being unset after it enters the while loop everything works fine for the first 3 arrivals
("1","1","1")
but when it hits
("4")
it does not go to the else statement since the (
$minCC
is not > 1) anymore.

I am not sure if there is something wrong with the if statement or the while loop I need help figuring out what's wrong. Thanks in advance.

$alpha = ["A","B","C","D"];
$arrival = ["1","1","1","4"];
$cpu = ["10","2","2","4"];
$final = array(); //start + finish
$inCC = array(); //final cc of inline related to falp
$outCC = array(); //final cc of inline2
$falp = array(); // final a
$start = 0;

$tempc = array(); // => temp for leftc
$tempa = array(); // => temp for lefta

$leftc = array(); // =>merge inCC & outCC
$lefta = array(); // =>merge falp

$hashed = mysql_query("SELECT Alpha FROM fcfs", $connection);
while($row = mysql_fetch_assoc($hashed)){
$hash[] = $row['Alpha'];
}
/////test
do{
$min = min($arrival);
$findmin = mysql_query("SELECT Alpha,CPU FROM fcfs WHERE Arrival='$min'", $connection);
while($fm = mysql_fetch_assoc($findmin)){
$ALPHA[] = $fm['Alpha'];
$minCC[] = $fm['CPU'];
}

/*while(count($minCC) > 0){*/
$keys = array_keys($arrival, $min);
foreach($keys as $k)
{
unset($arrival[$k]);
}
$min2 = min($arrival);
$diff = $min2 - $min;

if(count($minCC) > 1){ /// else fasfas el min of mincc
for($i=0; $i<$diff; $i++){
if($minCC[$i] == 1){
array_push($inCC, $minCC[$i]);
array_push($falp, $ALPHA[$i]);
unset($minCC[$i]);
unset($ALPHA[$i]);
unset($hash[$i]);
}else{
array_push($inCC, 1);
array_push($tempc, ($minCC[$i] - 1));
array_push($tempa, $ALPHA[$i]);
unset($minCC[$i]);
unset($ALPHA[$i]);
unset($hash[$i]);
}
}
}else{
array_push($inCC, $minCC[0]);
array_push($falp, $ALPHA[0]);
unset($minCC[0]);
unset($ALPHA[0]);
unset($hash[0]);
}
}while(count($hash) > 0); <=== think this goes infinite and page stop working


/* testing each array */
print_r($hash);
echo '<br>';
print_r($tempc);
echo '<br>';
print_r($tempa);
echo '<br>';
print_r($inCC);

Answer

I have not reviewed you code very carefully, but what I already see is that seems like you believe that unset($hash[i]) shifts numeric keys remaining elements. So bad news that it DON`T.

Look, if you have such array and make such unset

$a = array(10, 20, 30);
unset($a[1]);

then

echo count($a); // returns 2
echo $a[0]; // 10
echo $a[1]; // undefined
echo $a[2]; // 30

so such construction wount work clean array as expected... it even wound end

while(count($a))
    unset($a[0]); // delete $a[0] if exists, or delete nothing if array doesnt have $a[0], even if it has $a[1];

you code is more complicated, but I guess it based on the same incorrect assumption.

update

you could close index gaps with

$hash = array_values($hash);

after each unset on this array to fix this problem;

Comments