PHP Functions
In one of the previous slides, we used a function called count($arr)
that would return the number of items inside that array. So this is a PHP defined function, but we can also create our own functions.
First, we write function
, and then we give this function a name. Then we do open and closed parentheses ()
, and we do our curly braces.
function greeting(){
echo 'Welcome to the world of PHP';
}
We can now call this greeting function wherever we want, and the code inside these curly braces will be executed. So let's go ahead and add this greeting down inside of our HTML.
<?php
function greeting(){
echo 'Welcome to the world of PHP';
}
?>
<!DOCTYPE html>
<html>
<head>
<title>My First PHP App</titile>
</head>
<body>
<h1><?php greeting(); ?></h1>
</body>
</html>
There are a bunch of other things you can do inside of your function, such as accept arguments. So in our count
function, we were able to pass an array, but we can also specify many arguments that we want to pass inside our function. Let's pass a name variable so that it can greet the name we give it.
<?php
function greeting($name){
echo 'Hello ' . $name;
}
?>
<!DOCTYPE html>
<html>
<head>
<title>My First PHP App</titile>
</head>
<body>
<h1><?php greeting( "DevDojo" ); ?></h1>
</body>
</html>
We need to specify a name inside of our greeting function, so when we call our function, since we have an argument inside of the function declaration, we need to pass a value for that argument. In the example above, we passed in the string "DevDojo".