0

How can I loop inside an array in my code?

This is the static version of my script:

$val=array(
array("value" => "Male","label" => "Male"), 
array("value" => "Female","label" => "Femal"),  
);

my_form("Gender","select","gender",$val,"",5);

Then, I need to retrieve the value and label from the database.

So I customized my previous code to:

$div=array(
while($h = mysql_fetch_array($qwery)){
array("value" => "$h[id]","label" => "$h[div]"),    
}
);

my_form("Division","select","id_div",$div,"",5);

When I run it I get this Error message:

Parse error: syntax error, unexpected 'while' (T_WHILE), expecting ')'

Can anyone help me?

I want to loop the join data from my database into :

input type="Select"

2
  • 1
    You can't loop inside an array Commented Nov 11, 2016 at 8:54
  • 1
    Why is this tagged java ? Commented Nov 11, 2016 at 9:14

2 Answers 2

2

You can't use a loop directly as a value in an array. Instead, loop over and add each array for each iteration of the while-loop.

Using $div[] = "value", you add that value as a new element in that array.

$div = array(); // Initialize the array 

// Loop through results
while ($h = mysql_fetch_array($qwery)) { 
    // Add a new array for each iteration
    $div[] = array("value" => $h['id'], 
                   "label" => $h['div']);
}

This will create a two-dimensjonal array which would look (as an example) like

array(
    array(
        "value" => "Male",
        "label" => "Male"
    ), 
    array(
        "value" => "Female",
        "label" => "Female"
    )  
);

...which you then can look through with a foreach to do what you want with it.


If you want this to be output as options in a select-element, you could just do that directly

<select name="sel">
    <?php 
    while ($row = mysql_fetch_array($qwery)) { 
        echo '<option value="'.$row['id'].'">'.$row['div'].'</option>';
    }
    ?>
</select>
Sign up to request clarification or add additional context in comments.

Comments

0

ùsing a foreach can help you out. It gives you alot more overview imho.

$values = array(
    array("value" => "Male","label" => "Male"),
    array("value" => "Female","label" => "Femal"),
);

<select name="Select">
<?php foreach ($val as $item): ?>
    <option value="<?= $item['value']; ?>"><?= $item['label']; ?></option>
<?php endforeach; ?>
</select>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.