Return first key in foreach

I have a problem with returning the first array key in foreach. I can return the $ key, but I cannot figure out how to return only the first key.

<td>
    <div align="center">
        <span class="formlist">
            <select id="plant" name="plant[]" class="form-control" multiple="multiple">
            <?php 
                $query_plant = "SELECT * FROM plant WHERE plant_enable=1 ORDER BY plant_name";
                $rs_plant = DB_Query($query_plant); 
                while ($row_plant = DB_FetchRow($rs_plant)) {
                    $plant.='<option name='.$row_plant["plant_shortname"].' value='.$row_plant["plant_id"].'>' .$row_plant["plant_name"].' ['.$row_plant["plant_id"].']</option>';
                }   
                mysql_free_result($rs_plant);
                echo $plant;
            ?>
            </select>
       </span>
    </div>
</td>

if(isset($_POST['plant'])) {        
    $checkbox1 = $_POST['plant']; 
    $chk="";
    $stf_sql = "SELECT * FROM test_plant WHERE staff_id = '".$STAFF_ID."'";
    $stf_res = DB_Query($stf_sql);      
    if(DB_RowsReturned($stf_res) > 0) {
       $del_sql = "DELETE FROM test_plant WHERE staff_id = '".$STAFF_ID."'";
       $del_res = DB_Query($del_sql);
    }       
    foreach($checkbox1 as $chk1)  
    {  
        $in_ch="insert into test_plant(staff_id, plant_name, submit_dt) values ('$STAFF_ID','$chk1', Now())";  
        $in_res = DB_Query($in_ch);                
        $abc = mysql_query("SELECT * FROM test_plant");    
        while($abc_row = mysql_fetch_assoc($abc)) {
            foreach($abc_row as $key => $value) {
                echo $key; //return first key here
            }          
        }      
    }       
} else {
    echo "OK"; 
}

I tried to return $key[0], but it only returns the first letter. I want to return 'p_id'

My table structure:

+6
source share
2 answers

Like this,

$keys = array_keys($checkbox1);
print_r($keys); // for all keys
echo $keys[0]; // It will echo first key of the array.
+4
source

You can reset the pointer of the internal array, and then get the key of the current element:

reset($checkbox1);
echo key($checkbox1);

(Put this outside your outer while loop).

Or you can even get all the keys of the array, and then grab the current key:

echo current(array_keys($checkbox1));
0
source

All Articles