I am trying to surround strings in a php array with <p id=para>
and </p>
here is my code. Nothing happens when I run it.
foreach($i=0;$i < count($tags); $i++){
$tags[$i] = "<p id=para>" . $tags[$i] . "<p>";
}
Tags is my array of strings.
I am trying to surround strings in a php array with <p id=para>
and </p>
here is my code. Nothing happens when I run it.
foreach($i=0;$i < count($tags); $i++){
$tags[$i] = "<p id=para>" . $tags[$i] . "<p>";
}
Tags is my array of strings.
You need to do this instead.
foreach($tags as &$tag){
$tag = "<p id=para>" . $tag . "</p>";
}
The & references tag instead of copying it, which is your problem it won't change the string in the actual array.
There is a few issues in your code snippet.
First off: You are using a foreach-loop
, but supplying arguments as if it was a for-loop
.
You generate invalid
HTML, your id
attribute need to enclose the value in "
or '
, eg: id="para"
.
You'r <p>
tag is not closed, but instead followed by another <p>
tag (should be a </p>
).
You can use either a for-loop or a foreach-loop, but they work differently.
A for-loop would be written much like the one you got:
for($i=0;$i < count($tags); $i++) { ...
While a foreach would look more like:
foreach($tags as &$tag) { ...
Notice the &
sign before $tag
, the &
indicates that it is a reference to the object, that means, if you change the object inside the foreach loop
, it will actually be changed, not just inside the foreach
scope.
This means that you can edit the $tag
object right away instead of accessing it from the array.
If you rather access it from the array, but still wish to use a foreach
you can get both the index (the key) and the value by:
foreach($tags as $key => $value) {
$tags[$key] = 'html' . $value . 'endhtml';
}
You have to decide which of the loops you intend to use. At the moment it looks like you have mistaken for
& foreach
loops.
Luckily, this may be done by both ways.
for
loopfor($i = 0; $i < count($tags); $i++)
{
$tags[$i] = "<p id='para'>" . $tags[$i] . "</p>";
}
foreach
loopAs mentioned earlier, but without a real explanation:
foreach($tags as &$tag){
$tag = "<p id='para'>" . $tag . "</p>";
}
Where the &$tag
does a reference, not a copy, therefore it updates the string inside the array. The way you tried to do it, it would only change the copy of it.
And finally, one last thing - If I may recommend, start using apostrophes/quotes when specifying attributes of html tags. It is more clean, more valid and way better looking.
Either Use
for($i=0;$i < count($tags); $i++){
$tag[] = "<p id='para'>" . $tags[$i] . "<p>";
}
Or Use
foreach($tags as $tg){
$tag[] = "<p id='para'>" . $tg . "</p>";
}