Wednesday 5 September 2018

PHP Looping through Associative Array does not work as expected?

I am having a array like so and I am looping trough it like this:

$options = array();
$options[0] = 'test1';
$options[1] = 'test2';
$options[2] = 'test3';

  foreach($options as $x)
 {
 echo "Value=" . $x ;
 echo "<br>";
 }

It outputs as expected:
Value=test
Value=test2
Value=test3

Now I want to add some options to my array and loop trough them:
$options = array();
$options['first_option'] = 'test';
$options['second_option'] = get_option('second_option');
$options['third_option'] = get_option('third_option');

foreach($options as $x)
{
  echo "Value=" . $x ;
  echo "<br>";
}

But it does not work as I want. Because it outputs:
Value=first_option
Value=second_option
Value=third_option

So now i do not know how to access stored values using foreach from these guys? Something like:
Value=first_option='test'

So when I use print_r($options)
Output is:
Array
(
[first_options] => test
[second_option] =>
[third_option] =>
)
1


your loop should look like this:
foreach($options as $key => $val){
  echo "Val: ".$val;
  echo "<br/>";
}

0 comments:

Post a Comment