Welcome to S-Design
The home of your bespoke, professional, fast-loading, interactive, database-driven web presence.
Menu
PHP TUTORIALS


PHP Functions

Functions allow to to write a piece of code once, and then reuse it over and over again. This is not the same as PHP Loops which allow to to use the same peice of code a set number of times.

Lets take a look at the for loop we used in the previous PHP Loops chapter: <?PHP
$veg=array("peas","carrots","parsnips","potatoes","broccoli");

for($i=0;$i<count($veg);$i++){
echo $veg[$i];
}
?>

Now what if we wanted to print out not only the vegetable name, but include an image/photograph of that vegetable too. We could simply include the code for this inside the for loop, but that means we'd have to write it out each time we wanted to do the same thing in other scripts.
Instead, we can write a function once, to generate the image code of the vegetable images, and simply use it whenever we want, in any script we want.
Here's a simple function to generate an image tag from the vegetable name: <?PHP
function VegPic($vegname){
return '<img src="images/'.$vegname.'.jpg">';
}
?>
This simple function returns an image tag based upon what we send it in the $vegname variable. So if we called this function with VegPic('carrots');, it would return <img src="images/carrots.jpg">

Here's how to use the for loop and the function together: <?PHP
function VegPic($vegname){
return '<img src="images/'.$vegname.'.jpg">';
}

$veg=array("peas","carrots","parsnips","potatoes","broccoli");

for($i=0;$i<count($veg);$i++){
echo $veg[$i];
echo VegPic($veg[$i]);
}
?>
This would print out the name of the vegetable, followed by an image of the vegetable. (This assumes that you had previously created all of the vegetable images and stored them inside a directory called images!)

What if you need to go through the vegetable array and get the vegetable image, in a loop, many times over in scripts all throughout your website?
You could combine the loop and image fetching inside one function, like this: <?PHP
function VegPic($veg){
for($i=0;$i<count($veg);$i++){
echo $veg[$i];
echo '<img src="images/'.$veg[$i].'.jpg">';
}
}

$veg=array("peas","carrots","parsnips","potatoes","broccoli");
VegPic($veg);
?>
Here we simply pass the whole $veg array to the VegPic function and let it perform the loop and image creation.


Title