Reputation: 377
When the interpreter reaches $pDB->AddLine(5,"Test") it stops responding! It returns the following error "Fatal error: Maximum execution time of 30 seconds exceeded in ... on line 21" Am I missing something? Should I use array_push() instead?
<?php
class pDb{
protected $m_pArray;
public function __construct($arr){
$this->m_pArray = $arr;
}
public function RemoveLine($index){ // Todo
}
public function ReplaceLine($index,$input){
if(!$this->m_pArray)return -1;
$temp = array();
for($i=0;$i<count($this->m_pArray);$i++){
($i == $index) ? $temp[$i] = $input : $temp[$i] = $this->m_pArray[$i];
}
$this->m_pArray = $temp;
}
public function AddLine($index,$input){
if(!$this->m_pArray)return -1;
$temp = array();
for($i=0;$i<count($this->m_pArray);$i++){
if($i == $index) { $temp[$i] = $input;$i = $i-1; }else{ $temp[$i] = $this->m_pArray[$i]; }
}
$this->m_pArray = $temp;
}
public function Get(){ if($this->m_pArray)return $this->m_pArray; return null;}
public function GetLine($i){ if($this->m_pArray)return $this->m_pArray[$i]; return null;}
}
$file = file("db.ini");
for($i=0;$i<count($file);$i++){
echo $i.": | ".$file[$i]."<br/>";
}
echo "<br/>===================================================================================================================<br/><br/>";
$pDB = new Pdb($file);
#$pDB->ReplaceLine(5,"Test"); // Works!!!
$pDB->AddLine(5,"Test"); // Crash!!!
for($i=0;$i<count($pDB->Get());$i++){
echo $i.": | ".$pDB->GetLine($i)."<br/>";
}
?>
Fix : Change
for($i=0;$i<count($this->m_pArray);$i++){
if($i == $index) { $temp[$i] = $input;$i = $i-1; }else{ $temp[$i] = $this->m_pArray[$i]; }
}
to
$done=0;
for($i=0;$i<count($this->m_pArray)+1;$i++){
if($i == $index && $done!=1){ $temp[$index] = $input; $done=1;}elseif($done == 1){ $temp[$i] = $this->m_pArray[$i-1]; }else{ $temp[$i] = $this->m_pArray[$i]; }
}
Upvotes: 0
Views: 75
Reputation: 170
It seems to me that the last statement in this line in the for-loop of "AddLine" is the problem:
if($i == $index) { $temp[$i] = $input;$i = $i-1; }
As soon as $i reaches 5 (the $index from the function call), you always decrease $i, only to have it increased again by the loop, therefore never proceeding any further. Infinite loop -> timeout.
Upvotes: 1
Reputation: 49376
Consider your code...
for($i=0;$i<count($this->m_pArray);$i++) {
if($i == $index) {
$temp[$i] = $input;
$i = $i-1;
} else {
$temp[$i] = $this->m_pArray[$i];
}
}
If $i == $index
, then you promptly subtract one from $i
, and go around the loop again. This adds one to $i
, making it equal to $index
again, and you fall into the same case - forever! You either need to tie your loop condition to something you change in the if
branch (i.e. $temp
), or change the logic here completely.
Upvotes: 4