Reputation: 5674
I have a PHP array such as
$lulz = array ( 'tom', 'hojn', 'john', 'kiwi', 'tron', 'jikes')
I am outputting the array as follows via simple foreach
foreach ($lulz as $key) {
echo $key;
}
I would like to put different CSS classes per each output. so, for example, the output would be
$result = '<div class="one">$tom</div><div class="two">$hojn</div><div class="three">$john</div><div class="four">$kiwi</div><div class="five">$tron</div><div class="six">$jikes</div>';
the current path I am on is putting in an incrementer variable that is incremented ++ after each loop. that works - I get 1, 2, 3, etc - but I am not sure how to translate that to my CSS divs per each item; or if I am even on the right path.
i was hoping to output array such as:
foreach ($lulz as $key) {
echo $key[1];
echo $key[3];
}
where [1]
and [3]
are just the entry 1 and 3 in the array
but doesn't seem to be possible.
any help would be greatly appreciated.
Upvotes: 1
Views: 619
Reputation: 195
You can make your array as a class for each output.
Try this
$lulz = array ( 'tom', 'hojn', 'john', 'kiwi', 'tron', 'jikes');
foreach ($lulz as $key){
echo '<div class="'.$key.'">'.$key.'</div>';
}
Upvotes: 1
Reputation: 53674
If you can just use the incrementer in the class name and it doesn't have to be a word representation of the number, this will give you the desired output and your classes would be .el1
, .el2
, etc.
<?php
$result = '';
$lulz = array ( 'tom', 'hojn', 'john', 'kiwi', 'tron', 'jikes');
foreach ($lulz as $key => $value) {
$result .= '<div class="el' . ($key + 1) . '">' . $value . '</div>';
}
echo $result;
?>
Upvotes: 1
Reputation: 689
<?php
$lulz = array('tom', 'hojn', 'john', 'kiwi', 'tron', 'jikes');
$catz = array('one', 'two', 'three', 'five', 'eight', 'thirteen');
foreach($lulz as $k => $x) { echo '<div class="'.$catz[$k].'">'.$x.'</div>'; }
?>
or
<?php
$lulz = array(
array('tom', 'one'),
array('john', 'two'),
array('hojn', 'three'),
array('kiwi', 'five'),
array('tron', 'eight'),
array('jikes', 'thirteen')
);
foreach($lulz as $k => $x) { echo '<div class="'.$x[0].'">'.$x[1].'</div>'; }
?>
Upvotes: 0