php - Why I can't access the array element using it's key? -
i have bellow php while , for loop.
in while loop it's storing $ch_for data in $ch_for array.
using print_r array showing these value :
array ( [ch7] => 7 [ch8] => 8 ) and trying access array data in for loop using line :
echo $ch_for["ch{$x}"]; but it's showing error message : illegal string offset 'ch7' in ...
while , loop
$ch_for = array(); $ch_name = array(); while ( $fetchchannel = mysqli_fetch_array($getchannel) ) { $ch_id = (int) $fetchchannel['ch_id']; $ch_for[$fetchchannel['ch_name']] = htmlspecialchars($fetchchannel['ch_for']); $ch_name[] = htmlspecialchars($fetchchannel['ch_name']); } ($x=1; $x<=12; $x++) { if( in_array('ch'.$x, $ch_name)) { $sel = 'checked = "checked" '; echo $ch_for["ch{$x}"]; } else { $sel = ''; $ch_for = ''; } ?> <div class="checkbox form-inline"> <label><input <?php echo $sel; ?> type="checkbox" name="ch_name[]" value="ch<?php echo $x; ?>">ch<?php echo $x; ?></label> <input type="text" name="ch_for[]" value="<?php echo $ch_for; ?>" placeholder="channel details" class="form-control ch_for"> </div> <?php } result of var_dump(array_keys($ch_for));
array(2) { [0]=> string(3) "ch7" [1]=> string(3) "ch8" }
you're overwriting $ch_for in else-branch since first key ch7, hence first loop (ch1 not in $ch_name , triggers else) overwrites $ch_for.
Comments
Post a Comment