PHP Functions [#29] Code Dynamic Websites with PHP

preview_player
Показать описание
Lecture 29: Intro to PHP Functions

If you've made it this far, congratulations are in order! We've covered a lot of ground, and our PHP coding skills are becoming much more refined and skillful!

I'm going to go ahead and say that functions are the Meat n' Potatoes (vegetarian version: Beans n' Rice) of most programming languages; they are fundamental when cooking a tasty PHP dinner!

In PHP, there is a massive library (over 1000) of baked-in functions—pun intended—that do everything from printing text on your screen to adding information to a database, and much more!

It's good to know that there are two types of PHP functions: Built-in PHP Functions, and Custom Functions (you can write your own custom PHP functions!).

Remember echo and print? Those little guys are functions!

Important Facts about Functions


A function is a block of statements that can be used repeatedly in a program.
A function will not execute immediately when a page loads.

A function will be executed by a call to the function.
— w3schools

Let's take a look at the basic syntax of a function:

function functionName() {

// execute code

}

Please note: A function name can start with a letter or underscore (not a number). — w3schools

Hot tip: You can name the function whatever you wish! Just try and have it reflect what the function actually does.

PHP sort() Function

Let's take a quick look at the built-in PHP sort() Function. This function allows us to sort an array in alphabetical order.

First, let's create an array:

// Custom array

$dinner = array("Meat", "Potatoes", "Beans", "Rice");

Now let's run our array through the sort() function:

// Custom array

$dinner = array("Meat", "Potatoes", "Beans", "Rice");

// Add the array as a parameter to sort() function

sort($dinner);

Now all we have to do is echo our array on the screen, using a Foreach loop:

// Custom array

$dinner = array("Meat", "Potatoes", "Beans", "Rice");

// Add the array as a parameter to sort() function

sort($dinner);

// Echo the sorted array

foreach ($dinner as $ingredient) {

echo "$ingredient - ";

}

If coded correctly, the above will echo the array in alphabetical order:

Beans
Meat
Potatoes
Rice

DOWNLOAD COURSE FILES HERE
Рекомендации по теме
Комментарии
Автор

This is a novice comment, a do's and don't of syntax, or common logic/syntax errors would really help. Your method is great for building from the ground up. If, however, one were using existing code as a novice, do's and dont's really help. Not to mention common logic errors. For example the use of the double equal sign. Enjoyed the lessons. Can't wait till you teach how to write to a database table. 

k.cbaynes
Автор

Good day mr, I would like to ask if do you have an idea on how to block websites in a certain IP in PHP? I will be needing it for my capstone project. Your help is highly appreciated. Thanks :)

lancelottheknight
visit shbcf.ru