0

So I have an array as follows:

$months = array(
  '01' => 'January',
  '02' => 'Febuary',  
  '03' => 'March',
  '04' => 'April'
);

I am putting these into a form select and would like to do the following:

<option value="01">January</option> 

for each variable in the $months array.

Right now I have the following code with the result of: <option value="">January</option>

<?php foreach ($months as $month): ?>
  <option value=""><?php echo $month; ?></option>
<?php endforeach; ?>

I'm not really sure how to make use of the first variable in the array. Or if that is even possible. What is teh easiest way to do what I'm trying to do?

5 Answers 5

3

You're close. You're just missing the array key which can be used as follows:

foreach (array_expression as $key => $value)
    statement

So your code might look like:

<?php foreach ($months as $month_num => $month): ?>
  <option value="<?php echo $month_num; ?>"><?php echo $month; ?></option>
<?php endforeach; ?>

See foreach.

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

Comments

2

your array is key & value format, so just add key to your loop:

<?php foreach ($months as $key => $month): ?>
  <option value="<?php echo $key; ?>"><?php echo $month; ?></option>
<?php endforeach; ?>

See:: PHP Arrays

Comments

0

Try like this :

<?php foreach ($months as $key=> $month): ?>
  <option value="<?php echo $key;?>"><?php echo $month; ?></option>
<?php endforeach; ?>

Comments

0

You have to make your foreach loop as key value pair

<?php foreach ($months as $month_key => $month_val): ?>
  <option value="<?php echo $month_key; ?>"><?php echo $month_val; ?></option>
<?php endforeach; ?>

For more on key value pair refer Foreach loop with key=>value

Comments

0

Try this:

>> What you are not know is how to use key in the array.

<?php

$months = array(
  '01' => 'January',
  '02' => 'Febuary',  
  '03' => 'March',
  '04' => 'April'
);

      foreach ($months as $month_no => $month): ?>
          <option value="<?php echo $month_no; ?>"><?php echo $month; ?></option>
<?php endforeach; 

?>

Thanks!

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.