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]; }
}