PHP Reference
<!DOCTYPE html> <html> <body> <h1>PHP & Comments </h1> <?php //This is a single line comment # This is also a single line comment /* this however is a comment that goes over three whole lines */ echo "Hello World!"; ?> </body> </html>
- You do not have to declare variables – simply assign the variable a value.
- Variables start with the $ sign, followed by the name:
<?php $name = “Tessa Tiger”; $age = 10; $still_a_kid = true; ?>
- Variables names:
- must start with a $
- can contain only letters, numbers and underscores
- are case-sensitive
echo is used to print text to the screen - it can display HTML as well as variables. It is very useful.
<?php $txt1 = “we have had"; $txt2 = “rainy days and only"; $txt3 = “sunny ones."; $x = 5; $y = 2; echo "<h1>More Echo Stuff</h1>"; echo "<p>This week $txt1 $x $txt2 $y $txt3 Ready for sun!</p>"; echo "$x + $y is "; echo $x + $y; ?>
Variables in echo() statements
<?php echo"Your name is $name. <br> By the way, you are $age years old."; ?>
Or like this:
<?php echo">Your name is ".$name.".<br>By the way, you are ".$age ." years old."; ?>
Both work!
Commas in echo() statements
PHP is even more crazy in that you can use commas instead of dots in an echo() statement. This is the only place this works!
So, you can do this:
<?php echo">Your name is ",$name,".<br>By the way, you are ",$age ," years old."; ?>
But, not this:
<?php $name = $first," ", $last; ?>
The second will cause an error.
So, why just not use the dot notation all the time? Two reasons - easier to type a comma and PHP process it slightly faster. See...crazy.
View Full Topic
Inserting Line Breaks
There are several ways to insert HTML into PHP code. We are going to use doing line breaks as a simple way to show the different methods.
Just put it directly in the code.
<?php $name = "Charles"; $age = 15; echo"Your name is $name. <br> By the way, you are $age years old."; ?>
Will give you
2. Stop and start your PHP code.
<?php $name = "Fiona"; $age = 14; echo"Your name is $name."; ?> // See how the next line is outside of the PHP tags? Therefore, it can be straight HTML. // Otherwise - it needs to be part of the string in an echo() statement. <br> <?php echo"However, you are only $age years old."; ?>
That will give you this - looks just the same?
Data Types in PHP
- String
- Integer
- Float (decimals - also called double)
- Boolean - true or false
- Array
Number Data Types
- Integer – numbers that are whole – no decimal points.
$x = 5; $y = 2;
- Float – number with a decimal point
$x = 55.2; $y = 2.345;
String Data Type
A string is a series of characters written with quotes – either single or double.
$message1 = “Fiona is in this class”; $message2 = ‘Teo is in the class too’;
- If you do quotes inside a string – needs to be the opposite.
$s1 = “Kate’s a vampire”; $s2 = ‘Callahan”s a zombie’;
Boolean Data Type
$codingIsFun = true; $homeworkIsFun = false;
+ addition
- minus
* multiplication
/ division
Incrementing/Decrementing Operators
PHP supports some fun ways to increase or decrease a variable by the amount of 1. This can be very useful for counters or loops.
| Example | Operator | What Happens |
|---|---|---|
| ++$i | Pre-increment | Adds 1 to $i, then returns $i |
| $i++ | Post-increment | Returns $i, then adds 1 to $i |
| --$i | Pre-decrement | Subtracts 1 from $i, then returns $i |
| $i-- | Post-decrement | Returns $i, then subtracts 1 from $i |
To combine strings in one single string - we use what is called Concatenation. This combines the strings using one of two different notations.
- Dot Concatenation simply strings them together using the . in between strings. The basic syntax is:
$WholeString = $string1.$string2.$string3;
- Concatenation Assignment use the .= to add whatever is on the right hand side of the operator to the string that is on the left. The basic syntax is:
$LeftString .= $RightString1.$RightString2.$RightString3;
Got it? Maybe? Here are some examples:
$txt1 = “hi”; $txt2 = “Claire”; echo($txt1." ".$txt2); $txt1 .= " ".$txt2; echo($txt1);
Here are a few useful ones - but here is a full list from W3Schools.
| function | Description | Example | Output |
|---|---|---|---|
| strlen() | # of characters in string |
strlen("how long?") |
9 |
| str_word_count() | # of words in string |
str_word_count("how long?") |
2 |
| strtolower() | Make everything lowercase |
strtolower("Hi You") |
hi you |
| strtoupper() | Make everything uppercase |
strtoupper("hi you") |
HI YOU |
| UCwords() | Capitalize |
UCwords("hi you") |
Hi You |
| strrev() | reseverses |
strrev("how long?") |
?gnol woh |
Used to compare two or more values to see if they meet a condition. This comparison always returns a Boolean value of either true or false. Here are the operators you can use to compare values in PHP:
| Operator | Description | Example | Returns |
|---|---|---|---|
| == | equal to | 15 == 15 15 == 10 |
true false |
| === | equal to equal type |
15 === 15 15 === '15' |
true false |
| != | not equal | 10 != 15 10 != 10 |
true false |
| !== | not equal or equal type |
15!= 15 10 != '10' |
false true |
| > | greater then | 15 > 10 | true |
| < | less then | 15 >= 15 | true |
| >= | greater then or equal to | 10 < 10 | false |
| <= | less then or equal to | 10 <= 10 | true |
Logical Operators
Often you’ll need to compare and contrast multiple conditions.
- If you want all conditions to be true – use the and logical operator – &&.
- If you want at least one of the conditions to be true – use the or logical operator – ||
- If you want the condition to be the opposite – use the not logical operators or !
| Operator | Description | Example | Returns |
|---|---|---|---|
| && | and | (10 < 15 && 20 > 15) (10 < 5 && 20 > 15) |
true false |
| || | or | (5 == 5 || 6 == 5) (6 > 5 || 3 == 2 ) |
true false |
| ! | not | !(3 ==3) | false |
//check to see if the condition is met if ($temp> 70) { echo "Wear shorts!"; } elseif ($temp< 70 && $temp> 50){ echo "Sweater"; } elseif ($temp< 50 && $temp> 30){ echo "Fleece"; } else { //runs if all else are not true echo "Wear your winter coat!"; }
Creating & Accessing
//You create an array using the array() function $animals=array(); //Can also create and fill an array using array() function $kids = array(“Van”, “Indigo”, “Jack”, “Regine”);
To access the elements in an array – use the index number. Can store the element in a variable:
$kid1 = $kids[0];
Set any item of the array by doing this:
$kids[0] = “Tom”;
Print the Contents of an array
These two methods are used for debugging print_r() prints all the values and var_dump() prints values and data types.
$kids = array (“Van ”, “Indigo ”, “Jack ”, “Regine ”); sort($kids); print_r($kids); Output Array ( [0] => Indigo [1] => Jack [2] => Regine [3] => Van )
var_dump($kids); Output array(4) { [0]=> string(6) "Indigo" [1]=> string(4) "Jack" [2]=> string(6) "Regine" [3]=> string(3) "Van" }
indexed
Basic one- array has a numeric key so you access an item in the array using that index number.
$colors= array (“red ”, “blue ”, “green”); //access the items in the array using the index value - starting at 0 echo "Item 1 is ".$colors[0];
Associative
This type of array allows you to store information in pairs. Examples include: A list of students with grades or a list of states with capitol cities.
You use the key value to access the desired data value. In the example below, you use the name of the state as the key value to access its capital city.
Example
//create the array using key values and a new character - the => $capitals= array(“Alabama”=>"Montgomery", “Alaska"=>"Juneau”, “Arkansas”=>"Little Rock"); //access the items in the array using the key value echo "The capital of Alaska is ".$capitals["Alaska"];
Multidimensional
Basically arrays can be made of arrays!
$students= array ( array( "name"=> "Margot", "age"=> 13, "animal"=> "monkey", "food"=> "pasta" ), array( "name"=> "Hadley", "age"=> 13, "animal"=> "penguin", "food"=> "broccoli" ) ); //use the print_r() or the var_dump() statement to see content and structure
Here are a few useful ones - but here is a full list from W3Schools.
| function | Description | Example | Output |
|---|---|---|---|
| count() | # of elements in array |
count($kids) |
4 |
| sort() | sorts array |
sort($kids) |
|
| list() | Assign values in array to variables |
list($kid1, $kid2)=array("Jack","Jane") |
$kid1 has value of "Jack" and $kid2 of "Jane" |
| array_pop() | Deletes last element in array |
array_pop("$kids") |
If array held "Jack" and "Jane" - now holds "Jack". |
| array_push() | Adds item(s) to end of array |
array_[push("$kids,"Jamal"") |
Adds Jamal to array |
| strrev() | reseverses |
strrev("how long?") |
?gnol woh |
for Loops
<?php for ($x = 0; $x < 3; $x++) { echo "The number is: $x <br>"; } ?> Output: The number is 0 The number is 1 The number is 2
foreach Loops
<?php $summer = array(“camp”,”beach”,”pool”,”boredom”); foreach ($summer as $activity) { echo “$activity<br>"; } ?> Output: camp beach pool boredom
Nested Loops
You can place loops inside of loops - the outer loop only repeats after the inner loop is done.
for ($i=0; $i < 3; $i++){ for ($j=1; $j < 3; $j++){ echo "$i is ".$i." and $j is ".$j); } } The output will be: i is 0 and j is 1 i is 0 and j is 2 i is 1 and j is 1 i is 1 and j is 2 i is 2 and j is 1 i is 2 and j is 2
x = 1 while x <= 3: print (“The number is”, x) x +=1 Output: The number is 0 The number is 1 The number is 2 The number is 3
Remember - you can use break to exit a loop - but sparingly.
<?php $x = 1; while ($x <= 300) { echo “The number is: $x <br>”; $x++; if($x == 3){ break; } } ?> Output: The number is 0 The number is 1 The number is 2
function myFunction($a, $b) { return $a * $b; } var $x = myFunction(4,3); echo("the sum is " + $x);
<form action="script.php" method="post"> </form>
- action – where the form contents will be sent to - usually a PHP script written that processes the data and does something with it.
- method – specifies the way the information will be sent - get or post.
The get Method
This is the default method that is used. It attaches the forms information onto a web address so that it is visible in the URL. For example if a form asks for a first and last name like this:
<form name="form1" action="myscript.php" method="get"> <p>First Name:<input type="text" name="firstName"></input></p> <p>Last Name:<input type="text" name="lastName"></input></p> <input type="submit" name="submit" value="submit"> </form>
This URL is sent to the web browser:
https://labcatscode.com/myscript.php?firstName=Jack&lastName=Bartlett
Anyone can see the information - used with short forms and forms that do not contain sensitive or private information. Often used with search queries.
Getting Values using the GET Method
To retrieve and store the form values in a variable name, your PHP would look like this:
<?php $firstName = $_GET[‘firstName’]; $lastName = $_GET[‘lastName’]; ?>
The Post Method
This method essentially sends the information invisibly to the script which processes it. Used when you are sending lots of information or sensitive information - especially passwords.
Every input element must have a name attribute to be sent correctly with this method. That is so the script that receives it can figure out which field the data belongs to.
Getting Values Using the POST Method
- If we have a form input called first_name that was sent via POST, would be stored as $_POST['first_name'].
In this example, your input field would look like this:
First Name:<input type=“text” name=“firstName”>
In your PHP script, you would retrieve and store the form value in a variable like this:
$firstName = $_POST[‘firstName’];
Redirecting a form to itself - SAFELY
Use this in your action value to redirect the form back to the same PHP page.
Storing your Password
Use the bit of code below to turn the password into as hashed version - then store the hashed version in the database.
$hashed_pwd = password_hash('mypassword', PASSWORD_DEFAULT);
Verifying The Password
When you need to verify it you can pull it out using the password_verify() function which has this basic syntax:
password_verify(string $password, string$hashed_password):bool
This will return false if the passwords did not match and true if they did.
if (password_verify('mypassword', $hashed_pwd)) { echo 'Password is valid!'; } else { echo 'Invalid password.'; }
Function names should:
- start with a verb
- describe what the function does
- use the CamelCase naming convention
- Examples:
function GetRecords() function CreateUser() function ViewTable()
Variable names should:
- describe what type of information or data the variable holds
- be written using lowercase with underscores - no spaces!
- avoid using ambiguous variables like $i or $x unless you are doing a simple index or counter in a loop!
