简体   繁体   中英

Special treatment to part of PHP array

I want to add a special class to the a certain entry of an array value. What do I need to add to that value in the array to give it's 'li' a special class?

I have an array like this:

"notes" => [
    "$100.00 Credit to Use at Any of",
    "the Domestic Bliss Spa Locations",
    "$100.00 Value",
    "Another list item",
    "yet another list item"
]

And I loop through these to spit out html like this:

<?php foreach ($slide['notes'] as $note): ?>
    <li><?= $note; ?></li>
<?php endforeach; ?>

I want the value $100.00 Value to have a special class.

Try this:

<?php foreach ($slide['notes'] as $note): ?>
    <li <?php if ($note == "$100.00 Value") echo "class='specialClass'" ?>><?= $note; ?></li>
<?php endforeach; ?>

Here you can check for multiple values like this way as :

<?php 
foreach ($slide['notes'] as $note) {
$values = array("$300.00", "$200.00", "$100.00", "$55.00");
if (in_array($note, $values))
{
echo  "<li class='special_class_name'>$note</li>";
} else {
    echo  "<li>$note</li>";
}
}
?>

You can use strpos to check if $note contains $100.00 Value and use the ternary operator , like this:

<?php
foreach ($slide['notes'] as $note){
echo (strpos($note, '$100.00 Value') !== false) ? "<li class='someClass'>{$note}</li>" : "<li>{$note}</li>";
}

Ideone Demo

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM