1

Can anyone explain, how this cat array is getting the id and name?

foreach ($all_categories as $menu) { ?>
<input type="checkbox" id="cat_<?php echo $menu->id; ?>" value="<?php echo     $menu->id.'_'.$menu->name; ?>" name="cat[]">
..
..
}

and i can get the id and name in controller,by using like below. It is working totally fine. My question is, how id went to cat array in position 0,and name position 1?

$res_arr=explode('_',$value);
$cat_id=$res_arr[0];
$cat_name=$res_arr[1];
  • You are splitting the value by `_`. So if it is `1_aaa` then `$res_arr[0]` will be `1` & $res_arr[1] will be `aaa`. – Sougata Bose Sep 18 '15 at 04:36

1 Answers1

0

The explode function returns an array either it finds the delimiter or not. You gave a string to explode and asked it to split the string wherever it sees '_'. So in your case there was only one '_' and explode sliced the string into two pieces and placed them in an array respectively at [0] and [1].

Edit:

<?php
foreach ($all_categories as $menu) {
print "<input type=\"checkbox\" id=\"cat_".$menu->id."\" value=\"".$menu->id."_".$menu->name."\" name=\"cat[]\"/>";
}
?>

php short tag is not recommended Link

Community
  • 1
  • 1
Scorpion
  • 396
  • 2
  • 14
  • 1. id="cat_id; ?>, why i can't write like this,without echo? id="cat_ $menu->id??? 2.name="cat[]", is it work like that? for first iteration of this loop, name is cat[0],for 2nd iteration of loop,name is cat[0] and so on ?? – Aruna Chakraborty Sep 18 '15 at 05:01
  • 1
    1. if you want to write without `echo`, you have two choices; either use `id="cat_=$menu->id?>"` or do not break the php tag and print everything. Let me edit the answer for this one. 2. name="cat[]" does not work like this here. It tells the browser that there are more elements with the same name and send them as an array when sending form. – Scorpion Sep 18 '15 at 05:15