phpajaxcodeigniterforeach

Message : undefine Offset : 10 from codeigniter


I Have Problem function for in controller, form more code like bellow :

i send data iddata with ajax to controller "Update_Kebutuhan_ke_Terpasang"

http://localhost/gishubkbm/Terpasang/Update_Kebutuhan_ke_Terpasang?iddata=[1,2,16,15,17,3,14,5,9,11]

code in Controller like bellow :

$iddata=array();
$iddata=array($_GET['iddata']); //value [1,2,16,15,17,3,14,5,9,11]
$a=explode(",", $iddata[0]); //explode value iddata
$b=preg_replace('/[^A-Za-z0-9\-]/', '', $a);
$jumlahdata=count($b);
for($i=0;$i<=$jumlahdata;$i++)
{
    $c=$b[$i]; // **problem here with message undefined offset : 10**
    $data=array('id_perjal'=>$c);
    $this->M_perjal_terpasang->save($data);
}
echo json_encode(array("status" => TRUE));

but all Proses run, data can input on database.


Solution

  • More than one things need to change. Check the comments and code like below:-

    $iddata=array();
    //$iddata=array($_GET['iddata']); //value [1,2,16,15,17,3,14,5,9,11]   this line not needed
    $a=explode(",", $_GET['iddata']); //explode whole $_GET['iddata']
    
    $jumlahdata=count($a); // count the length
    for($i=0;$i<$jumlahdata;$i++) // remove = to sign so that it iterates only 10 times from 0 to 9
    {
        if(!empty($a[$i])){ // still check variable is set and have value
            $b=preg_replace('/[^A-Za-z0-9\-]/', '', $a[$i]); // do the replacement here on each array value,not just one outside
            $c=$b;
            $data=array('id_perjal'=>$c);
            $this->M_perjal_terpasang->save($data);
        }
    }
    echo json_encode(array("status" => TRUE));