Reputation: 1879
So i have a problem with taking an array and looping through the values and outputing with a foreach statement.
code
<?php
$example = array("test" => "hello world" );
foreach ($example as $arr) {
printf("<p>what do you have to say for yourself?</p><p>%s!</p>",$arr["test"]);
}
?>
hoping to get the output:
what do you have to say for yourself?
hello world!
Instead get
what do you have to say for yourself?
h!
why just the single character?
Any help would be great
thanks
Upvotes: 1
Views: 788
Reputation: 15374
Your foreach loop is already going through the values of the array, so don't reference the value again using the key:
<?php
$example = array("test" => "hello world" );
foreach ($example as $key => $val) {
printf("<p>what do you have to say for yourself?</p><p>%s!</p>",$val);
}
?>
From your other example in the comments, you would not be able to use a loop because the placements are very specific. Instead reference each value specifically without a loop:
$example = array(
"first" => "Bob",
"last" => "Smith",
"address" => "123 Spruce st"
);
printf("<p>my name is %s %s and i live at %s</p>",
$example['first'],
$example['last'],
$example['address']
);
Upvotes: 5
Reputation: 430
Foreach assumes there is more than one element in the array. If not just echo out the element like echo $example['test']; No need for a looping construct. If more than one element:
$example = array('text'=>"what do you have to say for yourself?",'test' => "hello world" );
print_r($example);
foreach ($example as $value)
printf("<p>%s!</p>",$value);
foreach is assigning the value of an array element to a variable called $value on each loop. Make sense?
Upvotes: 0
Reputation: 1001
Perhaps looking at it this way will help;
<?php
$example = array("test" => "hello world", "foo" => "bar");
foreach ($example as $key => $val) {
# option 1
echo "<p>what do you have to say for yourself?</p><p>$key => $val</p>";
# option 2
echo "<p>what do you have to say for yourself?</p><p>$key => $example[$key]</p>";
}
?>
Once you see how it iterates through, you can put your statement back into printf() or do whatever with the variables.
Note that if you have multidimensional arrays, you can refer to the next level of the array by addressing the key;
Upvotes: 1
Reputation: 1094
Looping over your associative array is putting a value in $arr
each iteration. When you try to index into $arr you're actually indexing into a string, hence the single character.
Upvotes: 0