Search code examples
phpsession-variablesflash-message

flash messages function with arrays not working


Trying to modify a flash message function, but it is not working whatsoever. Is the $_SESSION[$type][$name] and so on format not acceptable?

function flash($type = '', $name = '', $message = '', $class = '', $dismiss = '' )
{
//We can only do something if name exists
if($name)
{   
    //No message, create it
    if($message && empty($_SESSION[$type][$name]))
    { 
        $_SESSION[$type][$name] = $message;
        $_SESSION[$type][$name][$class] = $class;
        $_SESSION[$type][$name][$dismiss] = $dismiss;
    }
    //Message exists, display it
    else if($_SESSION[$type][$name] && empty($message))
    {
        echo '<div class="'.$_SESSION[$type][$name][$class].'">'.$_SESSION[$type][$name].' '.$_SESSION[$type][$name][$dismiss].'</div>';
        unset($_SESSION[$type]);
    }
}
}

Usage would be :

// set a message
<?php flash( 'error', 'test', 'whats up?', 'info', 'TRUE' ); ?>

// display a message
<?php flash( 'test' ); ?>

Solution

  • I think the problem you're having is you're overwriting the $message with an array here:

    $_SESSION[$type][$name] = $message; // Sets the message
    $_SESSION[$type][$name][$class] = $class; // Overwrites it with an array
    

    All you'll need to do is save the message to the same array (and make sure the index you give it can never be the same as $class or $dismiss. So for example:

    $_SESSION[$type][$name]['messagetext'] = $message;
    

    Then, of course, update the display part of the code to use that index:

    echo '<div class="'.$_SESSION[$type][$name][$class].'">'.$_SESSION[$type][$name]['messagetext'].' '.$_SESSION[$type][$name][$dismiss].'</div>';
    

    EDIT: After the discussion in the comments, the final code could look like this provided there is only going to be one message per $type and $name combination:

    function flash($type = '', $name = '', $message = '', $class = '', $dismiss = '' )
    {
    //We can only do something if name exists
    if($type)
    {   
        //No message, create it
        if($message && empty($_SESSION[$type][$name]))
        { 
            $_SESSION[$type][$name]['message'] = $message;
            $_SESSION[$type][$name]['class'] = $class;
            $_SESSION[$type][$name]['dismiss'] = $dismiss;
        }
        //Message exists, display it
        else if($_SESSION[$type] && empty($message))
        {
            foreach($_SESSION[$type] as $name=>$array) {
                echo '<div class="'.$_SESSION[$type][$name]['class'].'">'.$_SESSION[$type][$name]['message'].' '.$_SESSION[$type][$name]['dismiss'].'</div>';
            }
            unset($_SESSION[$type]);
    
        }
    }
    }
    

    Usage would be:

    // set a message
    <?php flash( 'error', 'test', 'whats up?', 'info', 'TRUE' ); ?>
    
    // display all $type= 'error' messages
    <?php flash( 'error' ); ?>