PHP Bootstrap Alert Function


Many times, I have had to create a bootstrap alert in my web applications. So many in fact, I started writing a php function that can create it for me. Here is my snippet.

This is the function you can use throughout your code:

// returns a bootstrap alert
function getAlert($message, $alertType = 'success') {
  return "
  <div class=\"alert alert-$alertType alert-dismissible mt-5 mb-5 fade show\" role=\"alert\">
    <button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-label=\"Close\">
      <span aria-hidden=\"true\">&times;</span>

Then, whenever you need an alert, you can use it by doing this:

echo getAlert('Your message goes here', 'warning');


The $alertType defaults to success, but bootstrap offers several different options for the type of alert you have.


Further Reading

My Bootstrap Notes post contains several of my favorite bootstrap code snippets. Check it out!

© 2024 by Ryan Rickgauer