shibbir ahmed
shibbir ahmed

Reputation: 1024

Why I can't access the array element using it's key?

I have a bellow php while and for loop.

In while loop it's storing $ch_for data in $ch_for array.

Using print_r this array is showing these value :

Array ( [ch7] => Seven [ch8] => Eight )

And trying to access this array data in for loop using this line :

echo $ch_for["ch{$x}"]; 

But it's showing an error message : Illegal string offset 'ch7' in ...

While and For 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']);
}


for ($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"
}

Upvotes: 1

Views: 42

Answers (2)

Hikmat Sijapati
Hikmat Sijapati

Reputation: 6994

Your array is associative array.SO use in_array() in array_keys.Like this..

   <?php
$array = array('ch7'=>'Seven','ch8'=>'Eight');

$keys = array_keys($array);

//print_r($keys);

for ($x=1; $x<=12; $x++) {
    if(  in_array('ch'.$x,$keys)) {
        $sel = 'checked = "checked" ';
        echo $array["ch{$x}"].PHP_EOL;
    } else {
        $sel = '';
        $ch_for = '';
    }
}    

?>

Output:

Seven
Eight

Upvotes: 1

Kep
Kep

Reputation: 5857

You're overwriting $ch_for in your else-branch since the first key is ch7, hence the first loop (ch1 is not in $ch_name and thus triggers the else) overwrites $ch_for.

Upvotes: 0

Related Questions