0

I have a php object containing two arrays and I need to loop through both array at once and display option for select. The table->list should come inside the value and tables->title should come inside option HTML output.

Here is my code:

$tables = new \stdClass();
$tables->list =  ['bmg_contact_us','bmg_volunteer'];
$tables->title = ['Contact us', 'Volunteer'];

<select name="bmg-forms" onchange="submission_frm.submit();">

<?php
foreach ($tables as $key => $table) {
 echo "<option value='" . $tables->list . "'>'" . $tables->title . "'</option>";    
}
?>
</select>
5
  • in loop should be $table->list ? Commented May 1, 2019 at 8:22
  • What is your expected result? Commented May 1, 2019 at 8:22
  • The array $tables->list should come in value attribute of option and $tables->title array should come inside option Commented May 1, 2019 at 8:24
  • <option value="table_list"> table_title </option> Commented May 1, 2019 at 8:25
  • @AbhilashNarayan you can only accept one answer. Accept the answer suited you best Commented May 1, 2019 at 8:35

3 Answers 3

1

You need to loop the inner array and then use the key to get the title.

foreach ($tables->list as $key => $table) {
 echo "<option value='" . $table . "'>'" . $tables->title[$key] . "'</option>";    
}

Output:

<option value='bmg_contact_us'>'Contact us'</option>
<option value='bmg_volunteer'>'Volunteer'</option>

https://3v4l.org/i1dcT

Sign up to request clarification or add additional context in comments.

Comments

1
$tables = new \stdClass();
$tables->list =  ['bmg_contact_us','bmg_volunteer'];
$tables->title = ['Contact us', 'Volunteer'];
$options = array_combine($tables->list,$tables->title);//both array count must be same

Output:

Array
(
    [bmg_contact_us] => Contact us
    [bmg_volunteer] => Volunteer
)

html:

<select name="bmg-forms" onchange="submission_frm.submit();">

<?php
foreach ($options as $key => $value) {
 echo "<option value='" . $key . "'>'" . $value . "'</option>";    
}
?>
</select>

Comments

1

The easiest way would be to create an associated array (https://www.php.net/manual/en/language.types.array.php) and iterate over it.

In your example:

 $tables->options = [
    'bmg_contact_us' => 'Contact us', 
    'bmg_volunteer' => 'Volunteer'
 ];

 foreach ($tables->options as $value => $text) {
    echo("<option value='$value'>$text</option>");    
 }

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.