I have an array having various numbers:
$array = [1,2,3,4];
I would like to have some code that will extract those values and prepend 'ad' to them while imploding into an html attribute:
<div class="ad1 ad2 ad3">
How can I do that?
I have an array having various numbers:
$array = [1,2,3,4];
I would like to have some code that will extract those values and prepend 'ad' to them while imploding into an html attribute:
<div class="ad1 ad2 ad3">
How can I do that?
Combine implode()
with array_map()
to alter the values prior to imploding them.
Something like this:
$outputString = implode(' ',array_map(function($val) {return "ad{$val}";}, $inputArray))
Loop over your array, and do whatever you have to:
foreach ($array as $item) {
...
}
In your exemple:
$className = "";
foreach ($array as $item) {
$className .= "ad".$item." ";
}
echo '<div class="'.$className.'">';
You can either loop over it as Mathieu suggests, or do an implode statement:
$array = array(1,2,3,4);
if (sizeof($array)>0) {
$class = 'ad'.implode(' ad',$array);
}
echo $class; // ad1 ad2 ad3 ad4
Try this:
echo implode(' ad', $array);