How to make pHP tabs
Learn how to create PHP tabs with an example: create interactive interfaces and provide users with an organized view of information.
Creating PHP Tabs
Tabs are a great way to organize and navigate through content on a page, and can be easily created with PHP. This tutorial will show you how to create a basic tab structure with PHP and HTML.
First, let’s create an array containing the names of your tabs. For this tutorial, we’ll use three tabs named “Home”, “About”, and “Contact”.
$tabs = array('Home', 'About', 'Contact');
Next, let’s create a function that will generate the HTML for the tabs. This function will take the array of tab names as an argument and will loop through each one to generate a tab link.
function generateTabs($tabs) {
// Start the tab structure
echo '';
// Loop through each tab
foreach ($tabs as $tab) {
// Generate the HTML for the tab
echo '- ' . $tab . '
';
}
// End the tab structure
echo '
';
}
generateTabs($tabs);
The above code will generate a basic tab structure that looks like this:
Now that the tab structure is in place, let’s add some content for each tab. We’ll create a function for this, which will take the tab name as an argument and will generate the HTML for the content.
function generateTabContent($tab) {
// Generate the HTML for the tab content
echo '';
echo '' . $tab . '
';
echo 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.
';
echo '';
}
foreach ($tabs as $tab) {
generateTabContent($tab);
}
The above code will generate the HTML for each tab content, which looks something like this:
Home
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
About
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Contact
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Finally, let’s add some JavaScript to show and hide the tab content when a tab is clicked. We’ll use jQuery to make this easier.
$('.tabs a').click(function(){
// Get the tab name
var tab_name = $(this).attr('href');
// Show the tab content
$(tab_name).show();
// Hide all other tab content
$('.tab-content:not(' + tab_name + ')').hide();
// Prevent the link from acting like a normal link
return false;
});
And that’s it! You now have a functioning tab structure with PHP and HTML.