Having the following PHP array, how can I insert a string everytime the first character of the value of 'palabra' changes?
Array
(
[0] => Array
(
[palabra] => aaa
)
[1] => Array
(
[palabra] => abbb
)
[2] => Array
(
[palabra] => bbb
)
[3] => Array
(
[palabra] => ccc
)
[4] => Array
(
[palabra] => dddd
)
[5] => Array
(
[palabra] => eeee
)
)
I currently have something like so, but it just list
forearch ($word_array as $word) {
echo '<li>'.$word['palabra'].'</li>';
}
The desired result is something like
<h1>Words starting with A</h1>
<li>aaa</li>
<li>abbb</li>
<h1>Words starting with B</h1>
<li>bbb</li>
<h1>Words starting with C</h1>
<li>ccc</li>
Track first letter on every iteration and if it changes - output h1
:
$currentLetter = '';
foreach ($word_array as $word) {
$firstLetter = substr($word['palabra'], 0, 1);
if ($firstLetter !== $currentLetter) {
echo '<h1>Words starting with ' . $firstLetter . '</h1>';
$currentLetter = $firstLetter;
}
echo '<li>'.$word['palabra'].'</li>';
}
As a sidenote - having h1
as item of ul
will be considered as invalid markup .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.