How to get post values from form created using loop,
Here is my controller
$valuepost=$this->input->post('value');
if($valuepost==1){
$val1=array('NoOfinput' => $this->input->post('val1input'),'NoOfbox' => $this->input->post('val1box'),'boxvalue' => null);
$val=array($val1);
}
elseif($valuepost==2){
$val1=array('NoOfinput' => $this->input->post('val1input'),'NoOfbox' => $this->input->post('val1box'),'boxvalue' => null);
$val2=array('NoOfinput' => $this->input->post('val2input'),'NoOfbox' => $this->input->post('val2box'),'boxvalue' => null);
$val=array($val1,$val2);
}
elseif($valuepost==3){
$val1=array('NoOfinput' => $this->input->post('val1input'),'NoOfbox' => $this->input->post('val1box'),'boxvalue' => null);
$val2=array('NoOfinput' => $this->input->post('val2input'),'NoOfbox' => $this->input->post('val2box'),'boxvalue' => null);
$val3=array('NoOfinput' => $this->input->post('val3input'),'NoOfbox' => $this->input->post('val3box'),'boxvalue' => null);
$val=array($val1,$val2,$val3);
}
elseif($valuepost==4){
$val1=array('NoOfinput' => $this->input->post('val1input'),'NoOfbox' => $this->input->post('val1box'),'boxvalue' => null);
$val2=array('NoOfinput' => $this->input->post('val2input'),'NoOfbox' => $this->input->post('val2box'),'boxvalue' => null);
$val3=array('NoOfinput' => $this->input->post('val3input'),'NoOfbox' => $this->input->post('val3box'),'boxvalue' => null);
$val4=array('NoOfinput' => $this->input->post('val4input'),'NoOfbox' => $this->input->post('val4box'),'boxvalue' => null);
$val=array($val1,$val2,$val3,$val4);
}
echo val;
How to simplify this using loop or foreach , Please help with the solution required
Using (int) to cast your post value into an int.
$valuepost = (int) $this->input->post('value');
// declaring the array that will store the final result
$val = [];
// looping as many times as necessary
for ($i = 1; $i <= $valuepost; $i++) {
$val[] = [
'NoOfinput' => $this->input->post('val' . $i . 'input'),
'NoOfbox' => $this->input->post('val' . $i . 'box'),
'boxvalue' => null,
];
}
var_dump($val);
You also should check before looping if $valuepost is not to high (if you are sure that it won't be over 4 by example) :
if ($valuepost > 4) {
throw new \Exception('Must not be over 4.');
}
(an exception or a redirection)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.