Uptop 14 Uptop 14 - 5 years ago 261
PHP Question

PHP: how can I add a specific title to my flash message?

I'm working on a flash message with PHP, but I would like to have a specific title for each of my flash message. My container for the flash message is set in my header.php so I can use this system everywhere on my site:

<?php if(isset($_SESSION["flash-message"])): ?>
<?php foreach($_SESSION["flash-message"] as $type => $message): ?>
<div class="alert alert-<?= $type; ?>">
<p><?= $message; ?></p>
</div>
<?php endforeach; ?>
<?php endif; ?>


To execute it, I use this:

$_SESSION["flash-message"]["success"] = "Test";


So, I have that:

http://prntscr.com/a2ylze

Now, I would like to have a title, you know? Something like that:

$_SESSION["flash-message"]["title" = "The title"]["success"] = "The message"


Just something like that. I want the title above the message.

Answer Source

Short answer: use an array or object to store your message with corresponding title.

$_SESSION["flash-message"]["success"] = array("Title", "The Message");

And your code will be like following:

<?php if(isset($_SESSION["flash-message"])): ?>
        <?php foreach($_SESSION["flash-message"] as $type => $message): ?>
        <div class="alert alert-<?= $type; ?>">
            <h2><?= $message[0]; ?></h2>
            <p><?= $message[1]; ?></p>
        </div>
        <?php endforeach; ?>
    <?php endif; ?>

EDIT: And what happens if you have more than one success message? Your current code doesn't support multiple "same type" messages. It should be:

$_SESSION["flash-message"]["success"][] = array("Title", "The Message"); 

to store multiple "same-type" messages.

EDIT-2: You can also use object approach - more readable. Also contains multiple message ability I mentioned above.

<?php 
    $message = new stdClass();
    $message->title = "Title";
    $message->message = "The Message";
    $_SESSION["flash-message"]["success"][] = $message;
?>
<?php if(isset($_SESSION["flash-message"])): ?>
    <?php foreach($_SESSION["flash-message"] as $type): ?>
        <?php foreach ($type as $message): ?>
        <div class="alert alert-<?= $type; ?>">
            <h2><?= $message->title; ?></h2>
            <p><?= $message->message; ?></p>
        </div>
        <?php endforeach; ?>
    <?php endforeach; ?>
<?php endif; ?>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download