Anda di halaman 1dari 41

ADVANCED PHP

(STUDY GUIDE)
COURSE CONTENT

INTRODUCTION TO PHP..........................................................................................................................3
SO WHAT IS PHP?.........................................................................................................................................3
WHY PHP?...................................................................................................................................................3
WHAT IS A .PHP FILE?.................................................................................................................................4
WHAT IS MYSQL?.......................................................................................................................................4
WHERE TO START?.......................................................................................................................................5
OUTPUT, VARIABLES, & CHARACTERS...............................................................................................6
SIMPLE OUTPUT IN PHP:.............................................................................................................................6
ASSIGNING AND USING VARIABLES:............................................................................................................7
COMMENTING CODE:...................................................................................................................................8
SPECIAL CHARACTERS:................................................................................................................................9
DATA TYPES, MATH OPERATORS, & CONSTANTS..........................................................................12
DATA TYPES:..............................................................................................................................................12
MATH CONSTANTS:....................................................................................................................................14
MATH OPERATORS:.....................................................................................................................................16
MATH FUNCTIONS:.....................................................................................................................................19
IF, ELSE........................................................................................................................................................24
IF... EXPLANATION:....................................................................................................................................24
IF... CODE:..................................................................................................................................................24
COMPARISON OPERATORS:.........................................................................................................................26
LOGICAL OPERATORS:................................................................................................................................27
IF...ELSE IF...ELSE...:..................................................................................................................................28
ASSIGNMENT OPERATORS....................................................................................................................31
ASSIGNMENT OPERATORS:.........................................................................................................................31
WRITE YOUR OWN FUNCTIONS!.........................................................................................................35
FUNCTIONS WITHOUT ARGUMENTS:...........................................................................................................35
FUNCTIONS WITH ARGUMENTS:.................................................................................................................36
Scope:........................................................................................................................................................39
Introduction to PHP
To learn PHP, it is advised that you have a good understanding of HTML, basics of Web
Page Building, and some script knowledge (makes it easier to understand).

So what is PHP?
First off, PHP recursively stands for: Hypertext Preprocessor. This language is a Server-
Side Scripting Language, similar to ASP. That means all PHP scripts are executed on the
server (not on a user's browser).

All PHP scripts will be executed then the output (or result of the PHP scripts) will be sent
to the user. Now one great thing about PHP is its support for multiple Databases.
Databases are amazing storage devices for information. For example, databases can store
pictures, accounts, users, and more! Some Databases that PHP supports are: MySQL,
Informix, Oracle, Sybase, Solid, PostgreSQL, and Generic ODBC.

Also, PHP is an open-source language! Open-source means that the code used to make
the language is available to the public for their personal editing. So patches and upgrades
to PHP happen more frequently than projects that are not open-source. To webmasters,
what is probably the best part is that the language is free! PHP is free to download/install
on your server to use.

Why PHP?
PHP is a cross-platform language, meaning it works on many Operating Systems like
Windows, Linux, and Unix etc. It is compatible with almost all type of servers like IIS
(Windows Version), Apache (Linux Version). It is free to download off their website.
Finally, PHP is an easy language to learn. It was developed by programmers who wanted
an easier Server-Side language and PHP is that exactly. While being easy to learn, PHP is
efficient and can do many things.
What is a .PHP File?
PHP files, with an extension like .php, .php3, or .phtml, may contain text, HTML tags,
and scripting. Most files, when called by the browser, will only return HTML to the
browser because this language is a Server-Side language. The browser doesn't even know
how to read PHP, unless you have installed PHP on your own personal computer, which
is a rare case (normally people who want to experiment with PHP might do so).

What is MySQL?
Mysql? I thought I was here to learn PHP!? Well, you are. PHP + Mysql are simply
amazing. So having a good understanding of Mysql - helps!

Mysql is another open-source project, similar to PHP. It is a small database server for
storing information. Basically, a Mysql Server holds databases and inside these Databases
are Tables. Here is a screenshot of what a table looks like:

It resembles an Excel Spreadsheet. Each table is identified in a Database with a name.


Tables contain records (rows) with data and columns. A specific cell in a table is known
as a Field.

Where to Start?
Normally, if you have a paid host, they already got Mysql and PHP installed, but you
might want to contact them to make sure yourself. Also, a few "free" hosts have PHP
installed. I only know of one Free host that has PHP installed and gives you one Mysql
Database and that is OrgFree.
Also, if you have a computer, you can install an Apache server on a Windows or Linux
machine. I personally prefer Apache for the amazing amount of Add-on Modules you can
install. Then install PHP on windows or Linux machine. Finally, install Mysql on your
machine and you can run scripts off of localhost (your computer). The easiest way to
install an Apache Server on your Windows Computer along with PHP and Mysql is
WinLAMP or Xampp. A one-time installer makes it very easy. If you’re running Linux,
there should already be an auto-installer for Apache, so I suggest you contact the
programmers of your specific Operating System, as each form of Linux is different.

For webmasters, who write PHP, I highly suggest you at least install PHP and an IDE
program (text editor for programming, very helpful) that runs along with PHP. I use
Maguma which was made specifically to run along with a PHP-installed computer. Its
good because you can test your scripts before ever putting them online.

Well, that ends "What is PHP?" introduction. The following chapters will outline the
codes of PHP and will use PHP scripts to demonstrate the functionality of PHP. Have fun
everybody!
Output, Variables, & Characters

Simple Output in PHP:


PHP files normally include basic HTML and php scripting. Normally, webmasters use
PHP scripting to make their web pages dynamic like show the current time or maybe
show information about the Guest visiting or member of your website.

For example:

Example 1.1
<html>

<?php
echo "Hello Guest";
?>

</html>

That will simply output, Hello Guest (without quotations). The <?php and ?> lines starts
and ends the PHP code block.

In PHP, there are 2 ways to output text: echo (used in the example) and print. Personally,
I don't use print and normally stick with echo. In the above example, we would have an
output of Hello Guest. "Hello Guest" is a string being "echoed" by PHP.

Each line of PHP code ends with a semicolon. The semicolon simply indicates to the Web
Server where to parse a carriage return. If you wanted to, you could write endless PHP
code in one line! The Web Server, with PHP installed, would be able to read each code
line as if there were on separate lines thanks to the use of a semicolon.

Assigning and Using Variables:


Variables are used for many things. If you remember from Algebra Class, there are
variables such as X and Y that hold a value that would normally be a number. In PHP,
there are variables which you can assign values like numbers or strings.

For example:

Example 1.2
<html>

<?php
$phrase = "Hello Guest";
echo $phrase;
?>

</html>

Again, <?php and ?> start and end the PHP code block. In this example, we declare a
variable called phrase and then assign it a value. Each variable in PHP has the dollar sign
put in front $. Variables can store many values in PHP. You can call a variable whatever
you would like to call it as long as your characters are from the alphabet (lowercase or
uppercase) or use underscores and numbers (Variable Names like: $phrase, $number,
$someone4, $you_are_a_guest) You can have a number value, a string (that is what we
have in this example), or null and much more! For simplicity sake, we made a variable
called phrase whose value is Hello Guest.

Then we are going to output the variable phrase by using the echo command. You can use
single or double quotations around the data. In this example, we will have Hello Guest
outputted. Finally, see that after each line of PHP code (including the variable creation),
there is a semicolon at the end.

Commenting Code:
Commenting code is a way to leave notes in your code. It allows you to leave messages
in your code that will never be read or used during code execution. It is totally ignored.
Commenting code is a great idea and it is part of the software’s documentation! If you're
making a long script, then it's wise to comment your code so if you go back to that script
one day to update it, it will be easier to see what the code is doing due to the comments
and notes you leave or if you work on a PHP project with friends or co-workers, it's wise
to comment your code so if they need to update your work, its easier on them.

For example:

QUOTE
<html>

<?php

//This is a comment! Next I'm going to make a variable.


$phrase = "Hello Guest";

/*
This is a comment block.
I can hit enter as many times as I want.
Now I'm going to output the variable I just made
*/
echo $phrase;

#This is cool. We are done!


?>

</html>

Using the // code or # code will allow you to make a one line comment. If you want to

write a paragraph (large comment ) then it's wise to use the /* and */ code that starts
and ends a comment block.

Special Characters:
Now this is a great time to show you other printing (or echo'ing) capabilities. When your
echo'ing a string, you may include the following:

• \n (newline character, its like hitting the "enter" key on your keyboard)
• \t (tab, its just like you hit the "tab" key on your keyboard)
• \\ (displays a backslash \, its needed so its not confused as PHP code)
• \$ (displays a dollar sign $, if you don't use it, PHP will confuse this with a variable)
• \" (displays a quotation ", if you don't use it, PHP will think your ending the string)
• \0 through \777 (converts a character to hexadecimal of base 8 code)
• \x0 through \xFF (converts a chatacter to hexadecimal of base 16 code)

These are used for outputting purposes. Without the \" for example, there would be no
way of outputting a double quotation in a string that has " and " for the start and end. For
example:
QUOTE
<?php
$phrase = "Hello Guest";
echo "$phrase = " , $phrase;
?>

That would output:

CODE
Hello Guest = Hello Guest

Even though $phrase, is in between quotes, its still considered a variable thanks to the
dollar sign, so to output $phrase as a string and not the variable's assigned value, I must
do the following:

QUOTE
<?php
$phrase = "Hello Guest";
echo "\$phrase = " , $phrase;
?>

Using the backslash, in front of the variable (right in front of the dollar sign), PHP will
not consider that to be a variable anymore and just a regular word therefore I will get the
following:

CODE
$phrase = Hello Guest

That is why there are the other special characters for your use!

Note: It is very important to understand, if your displaying text in a browser (for people
who are experimenting PHP in a browser and not a command line), that you must format
your text using HTML tags. Sending line breaks, and tabs, will do nothing as the browser
will just take them out automatically. You must use your PHP scripts to send out proper
HTML formatted output.

That ends Basics 1 tutorial on PHP. I hope you enjoyed it! Feel free to ask questions.
Data Types, Math Operators, & Constants

This tutorial will go over basic Constants, More Information on Variables, and Math
Operators. The word choice I use is proper programming terminology. I have taken
classes for Programming so I would suggest, if you were to discuss Languages like PHP,
you would use similar terminology.

Data Types:
PHP comes fully stocked with Math Commands but to understand them, we need a good
understanding of using variables with values of numbers. In PHP, when you declare a
variable and assign it a value, it will automatically decide the way to store your data
internally. Behind the scenes, PHP supports eight data types:

• boolean (True or False)


• integer (holds integer values such as -9, 0, 2006 and etc.)
• float (for programmers, this is your “double”, it holds values like 3.1231 or 93.1231 and
etc.)
• string (shown in Basics 1, it holds text like “Hello Guest”)
• array (holds arrays of data items, will be discussed in later tutorials)
• object (hold programming objects)
• resource (holds a data resource)
• NULL (simply holds a value of NULL!)
*These were spelt in lower case because they are referred to in coding lowercase except
for NULL

Now you don’t have to worry about it almost 100% of the time, as PHP does this for you.
For example:
CODE
$variable = “You don’t have to say this is a string because PHP knows that!”;
$variable2 = 53.2341; //PHP will automatically store this as a float value
$variable3 = FALSE; //PHP will automatically store this as a boolean

There is no problem here, because PHP will store the data based on what you assign the
variable. Problems may occur when you begin to mix data types by adding a variable
with another. For example:

Example 2.1)
<html>

<?php
$variable = “42”; //PHP stores this as a string
$variable = $variable + 6; //PHP re-assigns a new value of 48 and stores it as an integer
$variable = $variable – 7.5; //PHP re-assigns a new value of 40.5 and stores it as a float
$variable = 2 + “8 Units”; //PHP re-assigns a new value of 10 and stores this as an integer
losing “Units”
?>

</html>

Now to avoid such things, don’t mix data types. Even if you still want to, PHP will
normally do it the way you want it, sometimes it won’t. Now there is a solution! You can
cast it by using a type cast! What this does is, it allows the programmer to specify the
data type for PHP to store the variable as.
For example:
CODE
$integer_var = (integer) $variable;
$float_var = (float) $variable;
$string_var = (string) $variable;

Now lets say you want to convert an integer to Boolean or some other data type to
boolean. The following are considered FALSE values:

• Default Value of boolean (when declared unless stated true)


• integer 0 is False
• float 0.0
• An empty string ($string = “”; //for example) or a string with a value of “0”
• An empty array (with no elements)
• Object with no member variables
• Special Type Null

Every other value and Data Types not mentioned are considered TRUE. Now lets go from
boolean to another Data Type!

• FALSE gives the value of 0 and TRUE gives the value of 1

Ok, now you are very versed in Data Types. Now to play with these Data Types and Math
Operators in code, but first lets define some constants!

Math Constants:
Now, lets say we want a variable to stay the same. We are going to define a variable with
a value and it will remain that, it will be a constant, whose value can't be altered! Now
this is very important in writing secure code! Defining variables is a great way to prevent
hacking. I suggest you pay attention here!

Creating Constants is easy, you use the define function, giving the constant a name and
assigning it a value.
For example:

CODE
define ("pi" , 3.1415926535);
define ("welcome_statement", "Hello Guest. I hope you enjoy my tutorials!");

Now, the name of the constant is always quoted. Then value you assign it only needs
quotes when you assign it a string value like the above example. Now to see a code
snippet:

QUOTE
<html>

<?php
//First, Create the Constant "pi"
define ("pi" , 3.1415926535);

//Now lets tell our visitor what pi's value is


echo "The Math Constant pi is ", pi, "!";
//Now we are Finished! Output is complete
?>

</html>

In the above example, the output would be this:

Example Above Output)


The Math Constant pi is 3.1415926535!

Now we can do the same thing for outputting a constant that has a string value.

Math Operators:
Oh no, not math! I hope your not thinking that, because math is very important when it
comes down to programming. If your a person who doesn't like math, how about you
program yourself some code that does math problems for you! It is possible in PHP as
PHP comes with many Math Functions for your use!

Now when programming Math into our code, we don't have to use variables. It is not
necessary:

CODE
echo "There are " , 1 + 2 + 3 , "tutorials";
Now we are not using only text. As you can see, the numbers are not in the quotes. We
would get an output of:

CODE
There are 6 tutorials

I think that is kind of boring. This would be considered hard-coding (it is static) so lets
use variables.

Example 2.2)
<html>

<?php
//Now lets make our variables
$php_tuts = 3;
$gimp_tuts = 4;
$flash_tuts = 9;

//We have created 3 integer variables. Let's output!


echo "Total Tutorials: " , $php_tuts + $gimp_tuts + $flash_tuts;
?>

</html>

*Live Example of Output


Ya, now we don't have something static. The output would be "Total Tutorials: 16" That
is cool! Now, PHP can do so much more. This is just adding. PHP has 5 Math Operators:

• + (adds two numbers)


• - (substracts one number from another)
• * (multiplies two numbers)
• / (divides one number by another)
•% (returns the remainder, when one number is divided by another (modulus))

Now, for the code example:

Example 2.3)
<html>

<?php
//Now lets use the Math Operators!
echo "5 + 5 = " , 5 + 5 , "<br />";
echo "5 - 5 = " , 5 - 5 , "<br />";
echo "5 * 5 = " , 5 * 5 , "<br />";
echo "5 / 5 = " , 5 / 5 , "<br />";
echo "5 % 5 = " , 5 % 5;
?>

</html>

The output would be:


CODE
5 + 5 = 10
5-5=0
5 * 5 = 25
5/5=1
5%5=0

Now, lets see something a little more advanced. Math Functions!

Math Functions:
PHP comes with tons of already built-in Math Functions for your use! Functions are
pretty much pre-programmed commands when you only have to give an argument. It will
be shortly explained in the code. Here is the list:

• abs (absolute value of a number)


• acos (arc cosine)
• acosh (inverse hyperbolic cosine)
• asin (arc sine)
• asinh (inverse hyperbolic sine)
• atan2 (arc tangent of two variables)
• atan (arc tangent)
• atanh (inverse hyperbolic tangent)
• base_convert (converts a number between bases)
• bindec (converts binary to decimal, a fun way to encrypt messages to friends)
• ceil (rounds a fraction up)
• cos (cosine)
• cosh (hyperbolic cosine)
• decbin (converts decimal to binary)
• dechex (converts decimal to hexadecimal)
• decoct (converts decimal to octal)
• deg2rad (converts degrees to radians)
• exp (calculates the exponent of e)
• expm1 (returns e^-1)
• floor (rounds a fraction down, known as "truncates")
• fmod (returns the floating point remainder of the division of the arguments)
• getrandmax (shows the largest possible random value)
• hexdec (converts hexadecimal to decimal)
• hypot (returns sqrt of var1 * var1 + var2 * var2)
• is_finite (determines whether a number is a legal finite number
• is_infinite (determines if a number/value is infinite)
• is_nan (determines whether a value is not a number)
• lcg_value (combined linear congruential generator)
• log10 (base 10 logarithm)
• log1p (returns log of 1 + a number)
• log (returns natural logarithm)
• max (finds highest value)
• min (finds lowest value)
• mt_getrandmax (shows the largest possible random value)
• mt_rand (produces a better random value)
• mt_srand (seeds the better random number generator)
• octdec (converts octal to decimal)
• pi (gets the value of pi, very accurate)
• pow (exponential expression)
• rad2deg (converts radians to degrees)
• rand (generates a random integer number)
• round (rounds a float)
• sin (sine)
• sinh (hyperbolic sine)
• sqrt (square root)
• srand (seed the random number generator)
• tan (tangent)
• tanh (hyperbolic tangent)

As you see, PHP has you covered! If you have taken a course of Trignometry (pre-
calculus and above too) you should recognize a lot of this stuff! These can be used to
program forumulas and etc. to help you out. Now how do you use Math Functions? Well
here are a few examples:

Example 2.4)
<html>

<?php
//Now lets use the Math Functions!

//Degrees to Radians Converter


echo "deg2rad(90) = " , deg2rad(90);

//Random Integer Output


echo "rand() = " , rand() , "<br />";

//What is the Square Root of 100?


echo "sqrt(100) = " , sqrt(100) , "<br />";

//Please round this float


echo "round(342.2342) = " , round(342.2342) , "<br />";
//tell me what PI is
echo "pi() = " , pi();

?>

</html>

What is inside the parenthesis is considered the argument. Not all Math Functions need
arguments as you can see. Here is a live ouput example (made because of the random
function). Now you can use Math Functions inside of Math Functions or assign a Math
Function's value to a Variable. Also, the argument may contain a variable or Math
Operators. See Example:

Example 2.5)
<html>

<?php
//Now lets use the Math Functions Again!
$variable = pi();
echo "round(\$variable) = " , round($variable) , "<br />";

//Now lets use Math Operators inside the Argument!


echo "sqrt(110-10) = " , sqrt(110-10) , "<br />";

//How about a Math Function inside a Math Function?


echo "round(exp(2)) = " , round(exp(2));
?>

</html>

Again, you can check out the live example for the ouput on this one (see the 2nd part). As
you can see, we can have arguments that are variables, contain Math Operators, and Math
Functions inside! The possibilites are endless!

Well, that ends my Basics 2 Tutorial! I hope you enjoyed it! The next tutorial, Basics 3,
will be alot shorter going over if, else statements and loops.
If, else...

So far, in the past 2 tutorials, our code has been "hard-coded," meaning that line, by line
all of our code will be executed and we already know the exact output no matter what
scenario. That is just no fun, I think...so this tutorial will show you how to make more
dynamic code when we code multiple situations and we are not 100% sure what the
output will be. So I present to you the Conditional If Statement!

If... Explanation:
The If statement is to run a test and execute code if the test is true. For example:

• If the dog is an animal, then give the dog some food.


• If clapping makes noise, then listen.
• If a doll is a human being, then shake its hand.

In the first example, "If the dog is an animal, then give the dog some food," the test
comes out True, because the dog is an animal, therefore we are going give the dog some
food. In the 2nd example, "If clapping makes noise, then listen," the test is True therefore
we are going to listen. In the last example, "If a doll is a human being, then shake its
hand," this test is False therefore we do nothing and move on.

As you can see, the "if statement" is used to run a test, to evaluate a scenario and if the
scenario or what Programmers call "an expression," is true then we must execute the
following code.

If... Code:
Now, hopefully you understand what the "If statement" does and its importance! Now lets
code one!
Example 3.1)
<html>

<?php
//Now lets declare a variable!
$var = 2;

if ($var == 2) //Expression We are Testing


{

echo $var; //Code Execute if the Expression is True

?>

</html>

In the above question, we are testing if the variable we created is equal to 2. If that is true,
all of the code between the { and } (brackets) will be executed therefore the code "echo
$var;" will be executed because our test is true, 2 is equal to 2. Therefore, our output is:

CODE
2
Comparison Operators:
Now, we can check for much more then just equality! These are the Comparison
Operators PHP has made for us!
Operator // Comparative Test
== // Check for Equality
!= // Check for Inequality
< // Less then...
> // Greater then...
<= // Less then or Equal to...
>= // Greater then or Equal to...

Therefore, in an If Statement we can check if the expression is: Equal, Inequal, Less then,
Greater then, Less then or Equal To, and Greater then or Equal to! Also, in the
expression, you don't have to do simple tests, you can do some Math inside an expression
and much more! Now lets code something again!

Example 3.2)
<html>

<?php
//Now lets declare a variable!
$var = 27;

if ($var % 2 != 0) //Expression We are Testing


{

echo "$var is an odd number!"; //Code Execute if the Expression is True


}

?>

</html>

^Example 3.2 Checks if a number is odd.

In the above example, we take the declared/initialized variable, $var, and find the
remainder of it in the expression and see if the remainder does not equal zero. If you
divide 27 by 2, you get 13 and a remainder of 1. Since, 1 does not equal zero, the
following code in the bracket is executed! This is all possible due to the comparison
operator "!=" which checks if something does not equal something else! Our output is:

CODE
27 is an odd number!

Logical Operators:
Now lets say you want to test "if a dog and a cat are animals, then feed them both water."
Well, that too is possible in one If Statement!

Operator // Does
&& // AND (both expressions must be true)
and // AND (both expressions must be true)
|| // OR (either expression must be true)
or // OR (either expression must be true)
xor // One True other False (out of the 2 expressions, one of them must be true while the
other is False)
! // NOT (checks if it is False, see following code example)

See example 3.3 for code use.

If...Else If...Else...:

Now, in PHP, you can run many tests in one if statement block! For example, if a dog is a
human, then shake his hand, else if a book is something to read, then open it, or else do
nothing. This is known as "Conditional Branching!" Now lets code using some Logical
and Comparison Operators!

Example 3.3)
<html>

<?php
//Now lets declare some variables!
$var = 8;
$boolean = true;

if ($var < 2 && $boolean == false) //Expressions We are Testing


{
echo "The first test is True!";
}

else if ($var != 8 || !$boolean)


{
echo "The second test is True!";
}

else if ($var >= 12 xor $boolean == true)


{
echo "The third test is True!";
}

else
{
echo "All of the Tests Failed!";
}

?>

</html>

Now to break that down. First, we declared two variables: an integer variable ($var)
which was assigned the value of 8 and the boolean variable ($boolean) which was set to
True.

Then, we begun the huge if block! The first test, it reads like this: If $var is less then 2
(false, 8 is greater then 2) and if $boolean equals false (which is also false because
$boolean is true) therefore the code in the following brackets is ignored and we move on!

In the 2nd test, it reads like this: If $var does not equal 8 (which is false because $var
does equal) or if $boolean is false (which is also false because $boolean is true) therefore
the following code in the brackets is also not executed and we move on.

Now we are at the 3rd test! It reads like this: If $var is greater then or equal to 12 (which
is false because 8 is less then nor equal to 12) or $boolean is true (which it is!!) then we
execute the following code in the brackets and the rest of the if block is ignored! Now, if
the first part of the expression ($var >= 12) was true, nothing would of been executed
because the 2nd part of that test was true also so since we were using the Logical
Operator xor which demands that one of the tests must be true while the other one must
be false, we would of skipped this code but since the first test was false and the 2nd true,
we exected the code in the brackets!

Finally, the last part introduces the "else" syntax which basically means, if all the code
tests or expressions are false then do this code. Since test 3 was true, this code is ignored
and we get the following output:

CODE
The third test is True!

Well, that ends this tutorial on If...Else Statements and I hope it helped you understand
them, and how to use them in many ways!
Assignment Operators

Ok, the last 3 tutorials were rather lengthy so this tutorial will be significantly shorter,
well as I write it, I plan on it.

Assignment Operators:
In Basics 1, we discussed about Declaring Variables and then Assigning them Values. You
were shown one Assignment Operator, "=" and now it is time to learn the rest!

Operator: =
Example: $var = 5;
Means: Variable, $var, now is assigned the value of 5 and stored as an integer.

Operator: +
Example: $var += 10;
Means: $var = $var + 10 (this is used for numbers)

Operator: .=
Example: $string .= "Good Bye"; (this is += but for strings)
Means: $string = $string . "Good Bye";

Operator: *=
Example: $var *= 2;
Means: $var = $var * 2;

Operator: -=
Example: $var -= 2;
Means: $var = $var - 2;
Operator: /=
Example: $var /= 2;
Means: $var = $var / 2;

Operator: %=
Example: $var %= 2;
Means: $var = $var % 2;

Therefore, the Assignment Operators we have are: "=", "+=", ".=", "-=", "*=", "/=", and
"%=".

*Tip* Becareful to not confuse the Assignment Operator "=" with the Comparison
Operator "=="! They are different! One assigns a value while the other compares values.

*Tip* Becareful to not confuse ".=" and "+="! Again, ".=" is for strings while "+=" is for
math values!

Basically, Assignment Operators can be used to assign values or update values, which can
be understood as assigning new, updated values! We take the current value of a variable
and do something to it, update it, then store the new value to the old variable! We updated
the variable with new information!

Ok, now lets write some code!

Example 4.1)
<html>

<?php
//Now lets declare some variables!
$quantity = 2; //we bought 2 fruits at the store
$fruits = "apples"; //we bought apples!

//Lets Echo what we bought so far!


echo "We bought $quantity $fruits!<br /><br />";

//Lets buy 3 oranges!


$quantity += 3;
$fruits .= ", and oranges";

//Lets Echo what we bought so far!


echo "We bought $quantity $fruits!<br /><br />";

//Lets return 1 orange (it looked gross) and buy 2 peaches!


$quantity -= 1; //gross orange, good bye
$quantity += 2;
$fruits .= ", and peaches";

//Lets Echo what we bought so far!


echo "We bought $quantity $fruits!";

?>

</html>

So we went shopping in that code example. First we bought 2 apples and told the user we
did. Then we bought 3 oranges and updated the 2 variables $quantity and $fruits and then
told the user how many fruits we bought and what kind so far! Finally, one orange was
gross so we returned it, subtracted one from the total fruits we bought and then bought 2
peaches and told the user! The output would be:

CODE
We bought 2 apples!

We bought 5 apples, and oranges!

We bought 6 apples, and oranges, and peaches!

I hope you enjoyed this much shorter tutorial on Assignment Operators! Feel free to ask
questions!
Write your own Functions!

Now if you remember the tutorial Basics 2, we went over pre-written Math functions that
are available for your use, but honestly, wouldn't you rather have your own functions!?
Well it is possible in PHP, like many other languages, to write your own functions!

Now in PHP, you can write Functions or you can write Functions that take Arguments!

Functions without Arguments:


Simply, functions are chunks of PHP code that can be runned multiple times. It is very
important to use these then writing code over and over again so you can limit file-size of
the PHP document to increase efficiency! Functions and variables together are really
what PHP is. To clearify, we have already learnt a few functions then just the math
functions like echo()! Since echo() is used so much, it is not required to have the
parenthesis after it (common characterisitic of a function), but it still is a pre-written
function.

So to make a function, you declare a function then write the identifier of the function
(name its referred as) and followed by parenthesis. Then it has curly brackets with all of
the code to be executed when that function is called.

Example 5.1)
<html>

<?php
//Now lets write a function!

function hello() //Declared a Function and gave it a name


{

//Now to write the code to be executed on call!


echo "Hello have a nice Day!";

//Now lets call the function!


hello();

?>

</html>

Ok, cool! We wrote a function. We could call it as many times as we want! The output of
that code is:

CODE
Hello have a nice Day!

Now, lets write functions that take arguments!

Functions with Arguments:


Now the parenthesis after the identifier (name) of a function can have variables inside to
pass information into the code of a function! The data inside the parenthesis is called
known as the "argument." You can have multiple arguments as well!
Example 5.2)
<html>

<?php
//Now lets create a variable!
$text = "I want this text to be big, bold, and underlined!<br />";

//Now lets write some functions with arguments!

function bigfont( $some_argument )


{
echo "<h2><b><u>$some_argument</u></b></h2>";
}

function sayHi( $username = "Guest", $msg = "Hello ", $end_msg = "<br />Have a Good
Day!" )
{
//Now to write the code to be executed on call!
echo $msg . $username . $end_msg;
}

function enter_twice()
{
echo "<br /><br />";
}

//Now lets call the functions!


bigfont ($text);

sayHi ("urmomma", "Hey ");

enter_twice();

sayHi ();

?>

</html>

*See Live Output For Output on this example, 5.2

In the above example, we feed the argument when we call the function so we can feed in
different things when we use the function multiple times! Basically, in code example 5.2,
we created 3 functions. Two of them took arguments (bigfont, and sayHi) while
enter_twice, was made just for my convenience.

bigfont( $some_argument) means that when you call the function, it takes one argument
and passes it to the code block. In the code block it uses that argument in an echo by
adding HTML styles to it. Notice how the argument's name ($some_argument) is the
same name as the variable used in the echo command.

function sayHi( $username = "Guest", $msg = "Hello ", $end_msg = "<br />Have a Good
Day!" ) is a function when we write default values for 3 arguments. That means, if we
don't pass arguments when calling the function, it will just use the ones pre-written. Also,
when feeding arguments, you don't have to give them all if they are already written like
sayHi() has! Later, when we call the function, we feed in 2 arguments to overwrite the
default values of $username and $msg! Finally, we call the function once more to see
what default values we have!

enter_twice() was a function that I didn't plan on writing in this tutorial but for
convenience, I went ahead and did it so when I ever have to output two <br />'s, all I have
to do is call that command Saves code, saves time, therefore writing better code!

Scope:
Object-oriented programmers will feel right at home here with the understanding of
"local" variables and scope. PHP has similar things, even though it isn't based on object-
orientation (even though you can make objects in PHP, to be discussed in the next
tutorial). Now for novice programmers, this may scare you, but realize, scope is to your
benefit!

Simply, when you declare a variable inside a function you wrote, it is now a "local
variable" meaning that the function with the variable declared inside it, is the only
function that can use it! Now there is a way to declare a variable in a function for other
functions to use and that is making the it a "global variable" which is as easy as putting
the word "global" infront of the variable's identifier during declaration! See the following
Example:

Example 5.3)
<html>

<?php

//Now lets write some functions with arguments!


function how_many( $apples, $oranges )
{

global $number;
$number = $apples + $oranges;
output_this();

function output_this()
{

global $number;
echo "We have $number apples and oranges.";

//lets call our functions!


how_many ( 4, 7 );

?>

</html>

For this, we must, in each function, declare the variable global. If we don't, the function
will create its own local variable. The output of that is:
CODE
We have 11 apples and oranges.

Well, that ends this tutorial on Functions and Scope! I hope you enjoyed it!

Anda mungkin juga menyukai