PHP Primer Documentation
Brief
This is a documentation on the basic fundamental terminology and principles of PHP. You might look at it as a vocabulary list with more detailed examples of usage.
PHP basics include the use of the following terms and concepts:
The Meat
$Variables
Define-it: Variables are like pockets of data. It is a container that can store strings, numbers, arrays, objects, or basically anything you want.
Notes: The easiest way for the math minded individuals to understand variables is like in algebra. A variable can be equal to a single number, or a whole equation. In other words, it represents something for future use.
PHP Variables start with the USD currency sign $. This indicates to the php engine you are declaring a variable. Examples of acceptable variable declarations are as follows:
<?php $myvariable = "my variable contents"; $Name = "George"; $personAge = 44; $camelCase = "works just fine"; $var_iable = "underscores accepted"; $AcceptedChars = "a-z A-Z 0-9 and _ but must start with a letter"; ?>
The following are INVALID variable declarations.
<?php $-coolvariable = 'cool content'; $1numbersFirst = 'no good'; ?>
There are also some other shortcuts and tricks with PHP Variables that are worth noting.
<?php
/*
These are called variable variables, can you guess why?
*/
// EXAMPLE 1
$a = 'varname';
$varname = 'Foobar';
echo $$a;
// will produce "Foobar"
// EXAMPLE 2
$b = 'hello';
$$b = 'class';
echo $b .' '. $hello;
echo $b .' '. $$b;
echo "$b ${$b}";
// will all produce "hello class";
/*
This is a shortcut to declare multiple variables to the same value
*/
$var1 = $var2 = $var3 = 'Value Here';
echo $var1;
echo $var2;
echo $var3;
// will all produce "Value Here";
?>
'Strings' will be "Strings"
Define-it: Strings are the coding term for data that is text consisting of words and numbers (alphanumeric characters). However strings can contain most any type of character. Certain special characters must be properly escaped.
Notes: Escaping characters just means you follow the appropriate rules for special characters to make sure that it doesn't break the string and/or code.
String delimiters in PHP consist of mostly 'single quotes' and "double quotes". Here are some examples of string declarations to variables (similar to the variables section):
<?php $string = 'Hello World I am a beautiful string.'; $string2 = "Just because I came second doesn't mean I am less beautiful"; ?>
Single Quotes used to declare a string becomes what is called a String Literal meaning everything within the single quotes will be displayed and or used exactly as is.
Double Quotes create an Interpolated String meaning that variables within this string will be interpolated, or replaced with their values. We will show examples of this below when we talk about displaying strings as output.
Notes: Printing, Echoing, or Outputting strings, whatever you wish to call it, is when the value of the variable or the string is returned to be displayed. The two most common PHP functions used to do this are echo and print and are completely synonymous. Here are some examples of returning strings including some string literals and interpolated strings.
<?php $Money = 'cash'; // String Literal $string = 'Hello World. $Money can be evil if you let it.'; //Output echo $string; print $string; // will both produce "Hello World. $Money can be evil if you let it." ?>
Code and Comment Blocks in PHP
Define-it: Code Blocks to start us off are any blocks of code identified as a php code with the <?php ?> tags as mentioned in the introduction
Here is an example of a block of code:
<?php
$scriptLanguage = 'php';
$version = '5.2.10';
echo "I am using $scriptLanguage version: $version";
?>
Define-it: Comment Blocks are blocks of text within a Code Block that the PHP engine will not interpret as code.
Notes: These comments make the code easier to read and understand and by default of most code editors that do color highlighting they will be gold or grey.
They can be used for self reference to the one that wrote the code, or to secondary eyes if the code is going to be shared.
Also Remember anything and everything, including <?php ?> tags will be commented out.
There are 3 different ways to insert comments into code blocks and are as follows:
1. The first is actually a Block as it explains in the comment:
<?php
/*
This is literally a Block for a comment and anything written
between the opening slash-asterisk and closing asterisk-slash
will be deemed as a comment. Even <?php ?> code tags!
*/
?>
2. The second is one you have seen frequently in the example blocks above in this article using the double slash
<?php // << This Double slash is actually a comment. // It will only comment out anything following on the same line this line would not be a comment, and would create an error ?>
3. Thirdly is maybe the fastest for a one-line comment using the hash or pound sign:
<?php # This is a comment ############ And so is this # and this # and this ?>
An Amazing Array of Arrays
Define-it: Arrays are basically variables that contain lists of information, or "arrays" of information including numbers, strings, and other arrays.
1. Numeric Arrays (default) are indexed by numbers starting with 0:
<?php
// Example 1
$names = array('Alex',"Bob","Charlie","Derek",'Zoolander');
// Example 2
$places[0] = 'School';
$places[1] = 'Church';
$places[2] = 'Work';
// Example 3
$misc = array('Hippo', 1400, 'Skadoopity doo');
?>
2. Associative Arrays are indexed by string values assigned by the coder:
<?php
// Example 1
$profile = array('name'=>'Alex Parker', 'age'=>112, 'height'=>'Ginormous');
// Example 2
$school['location'] = 'Iceburgland';
$school['zipcode'] = '12345';
?>
3. Multidimensional Arrays are simply arrays that contain arrays:
<?php
// Example 1
$superArray = array(
'uno' => array(
'first'=>'english',
'second'=>'korean',
'third'=>'spanish',
'what'=>'pig-latin'
),
'dos' => array(1,3,4,2),
'value'
);
echo $superArray[0];
// will produce "value"
echo $superArray['uno']['what'];
// will produce "pig-latin"
/*
Notice if the association is not assigned, it will
automatically be indexed with a numeric assignment starting at 0.
*/
?>
Operators for Operating in Operations
Define-it: Operators are the tools you use to do various "operations" in php including Assignments, Arithmetics (addition, subtraction, multiplication, division), and Concatenation.
Assignment operators will always include an = sign. Optionally arithmetic or concatenating operators maybe prepended to the = sign to assign and perform some sort of calculation or appending in one statement:
<?php // Basic $a = 20; // Additional Options $a += 2; # returns 22 $a -= 1; # returns 19 $a *= 3; # returns 60 $a /= 2; # returns 10 $a %= 7; # returns 6 (remainder) $a .= 0; # returns 200 (auto-converts to string) ?>
Comparison operators do exactly what they sound like they would: Compare two values.
<?php /*Basic Signs $x == $z Equal $x != $z Not Equal $x === $z Identical (Matching types ie. both strings or both numbers) $x !== $z Not Identical $x <> $z Not Equal $x > $z Greater than $x < $z Less than $x >= $z Greater than or equal to $x <= $z Less than or equal to */ //EXAMPLE 1 == '1' #returns true 1 === '1' #returns false 1 != '1' #returns false 1 !== '1' #returns true 1 > '2' #returns false ?>
Logical operators are mostly used in conditional statement to check multiple conditions at once.
<?php
/* Signs
Operator Name
----------------------
and And
or Or
xor Xor
! Not
&& And
|| Or
*/
//EXAMPLE
$e = (false || 'apple'=='apple');
// will be assigned a boolean value of true (1) if either condition is true;
$y = ($b && $x);
// will be assigned true if both $b and $x are true;
?>
Conditioning Your Conditional Statements
Define-it: Conditional Statements are where you put to use Comparison Operators and Logical Operators. They consist of if.. , if..else.. , if..elseif..else.. , and switch statements.
Notes: Conditional statements use one ore more comparisons, separated by logical operators all typically surrounded by parentheses
If statements:
<?php
if($bob == $bobFather){
$worried = true;
}
?>
If..else.. statements:
<?php
if($bob != $bobFather){
$worried = false;
} else {
$worried = true;
}
?>
If..elseif..else statements:
<?php
if($bob == $bobFather){
$worried = true;
$runAway = false;
}
elseif($bob == $bobMother) {
$worried = true;
$runAway = true;
}
elseif($age <= 15) {
$worried = true;
$runAway = true;
} else {
$worried = false;
$runAway = false;
}
?>
Switch statements take a single variable value to match against multiple cases. The code between the matching case expression and the following break; is executed:
<?php
$bob = 'sister';
switch($bob) {
case 'mother':
$gift = 'Rose';
break;
case 'father':
$gift = 'Grill';
break;
case 'brother':
$gift = 'Pocket Knife';
break;
case 'sister':
$gift = 'Shopping Certificate'; // this code will be executed
break;
default:
$gift = 'Buy myself something';
break;
}
?>
W3Schools.com Conditonal Statements
Loopy Loops
Define-it: Loops are used to run through a particular bit of code multiple times. They can either achieve either the same result repetitively or different results each time it runs through.
Notes: Loops are one of the harder things for individuals to grasp when first getting into learning a computer scripting or programming language for the first time.
Foreach Loops are used specifically on arrays to run the block of code for every element of the array:
<?php
$numbers = array('zero','one','two','three');
foreach($numbers as $key => $value) {
echo "index: $key has value: $value"."
\n";
}
/* will produce:
index:0 has value: zero
index:1 has value: one
index:2 has value: two
index:3 has value: three
*/
?>
W3Schools.com For & Foreach Loops
For Loops are used to just run a general loop independent of any particular variables except the one it initiates:
<?php
# SYNTAX
# for (initiate counter; stop when true; do after each loop)
$x = 100;
for($i=0;$i<5;$i++){
echo $x+$i."<br/>\n";
}
/* will produce:
100
101
102
103
104
*/
?>
W3Schools.com For & Foreach Loops
While Loops are used specifically on arrays to run the block of code for every element of the array:
Notes: While loops will try to continue looping forever if there is not something within the loop that causes the while condition to eventually become false.
<?php
$a = 0;
$b = 10;
while($a!=$b){
echo "a: $a | b: $b<br/>\n";
$a += 1;
$b -= 1;
}
/* will produce:
a: 0 | b: 10
a: 1 | b: 9
a: 2 | b: 8
a: 3 | b: 7
a: 4 | b: 6
*/
// HOWEVER
$a = 1;
$b = 10;
while($a!=$b){
echo "a: $a | b: $b<br/>\n";
$a += 1;
$b -= 1;
}
/* will continue to keep looping until the engine times out produces an error
This is be because when $b == 6 $a == 5. $a + 1 = 6 and $b - 1 = 5,
and so they cross over and try to continue forever
*/
?>
Login or Register to post a comment