PHP Programming/basics

From Wikibooks, open books for an open world
Jump to: navigation, search
This page makes use of Color Code Boxes. To leave your feedback regarding this new feature, please click here.

The Examples[edit]

Example 1 - Basic arithmetic operators[edit]

This example makes use of the five basic operators used in mathematical expressions. These are the foundation of all mathematical and string operations performed in PHP.

+ - * / =
add subtract multiply divide assign

The five mathematical operators all function identically to those found in C++ and Java

Examine this example. Each mathematical expression to the right of the assign operator is evaluated, using the normal order of operations. When the expression has been evaluated, the resultant value is assigned to the variable named to the left of the assign operator.

Crystal Clear app terminal.png PHP Code:

<?php
  $x = 25;
  $y = 10;
  $z = $x + $y;
  echo $z;
 
  echo "<br />";
  $z = $x / $y;
  echo $z;
 
  echo "<br />";
  $z = $y * $y * $x;
  echo $z - 1250;
  echo "<br />";
?>

Crystal Clear app kscreensaver.png PHP Output:

35<br />2.5<br />1250<br />

Crystal 128 yast default.png HTML Render:

35
2.5
1250


Crystal Clear action bookmark.png Note: If you are not familiar with (X)HTML, you may not know the purpose of this part of the above code:
echo "<br />";
Its purpose is to insert an HTML "line break" between the results, causing the browser to display each result on a new line when rendering the page. In the absence of this line, the above code would instead print:
352.51250

This is of course not the desired result.


There are two code options which perform the opposite of the assign (=) operator. The keyword null should be used for variable nullification, which is actually used with the assign (=) operator in place of a value. If you want to destroy a variable, the unset() language construct is available.


Examples:
$variable = null;

or

unset($variable);


Example 2 - String concatenation[edit]

This example demonstrates the concatenation operator (.), which joins together two strings, producing one string consisting of both parts. It is analogous to the plus (+) operator commonly found in C++ string class (see STL), Python, Java, JavaScript implementations.

The statement
$string = $string . " " . "All the cool kids are doing it.";
prepends the current value of $string (which is "PHP is wonderful and great.") to the literal string " All the cool kids are doing it." and assigns this new string to $string.


Crystal Clear app terminal.png Code:

<?php
  $string = "PHP is wonderful and great.";
  $string = $string . " " . "All the cool kids are doing it.";
  echo $string;
?>

Crystal Clear app kscreensaver.png Output:

PHP is wonderful and great. All the cool kids are doing it.

As we all know, or for those new to programming will soon find it, programmers are always searching for "tighter code". Simply put, we pride ourselves in doing the most work with the fewest keystrokes. With that in mind, here's a trick that can save those precious keystrokes: concatenate and assign at the same time. It's easy. Let's take the same example as above.

Crystal Clear app terminal.png Code:

<?php
  $string = "PHP is wonderful and great.";
  $string .= " " . "All the cool kids are doing it.";
  echo $string;
?>

Crystal Clear app kscreensaver.png Output:

PHP is wonderful and great. All the cool kids are doing it.

You just saved 8 keystrokes with the exact same output. Big deal? Imagine having to do that with 100 lines of template code like I did recently. Yes, it's a big deal. By the way, if you change the implementation without changing the output, that's known as refactoring. Get comfy with that term. You'll be using it a lot. See more examples of compound assignments below.

Example 3 - Shortcut operators[edit]

This snippet demonstrates self-referential shortcut operators. The first such operator is the ++ operator, which increments $x (using the postfix form) by 1 giving it the value 2. After incrementing $x, $y is defined and assigned the value 5.

The second shortcut operator is *=, which takes $y and assigns it the value $y * $x, or 10.

After initializing $z to 180, the subsequent line performs two shortcut operations. Going by order of operations (see manual page below), $y is decremented (using the prefix form) and divided into $z. $z is assigned to the resulting value, 20.


Crystal Clear app terminal.png Code:

<?php
  $x = 1;
  $x++;
  echo $x . " ";
  $y = 5;
  $y *= $x;
  echo $y . " ";
  $z = 180;
  $z /= --$y;
  echo $z;
?>

Crystal Clear app kscreensaver.png Output:

2 10 20
Crystal Clear action bookmark.png Note: The expanded version of the above code (without the shortcut operators) looks like this:
<?php
  $x = 1;
  $x = $x + 1;
  echo $x . " ";
  $y = 5;
  $y = $y * $x;
  echo $y . " ";
  $z = 180;
  $y = $y - 1;
  $z = $z / $y;
  echo $z;
?>
The output is the same as seen in the above example.


New Concepts[edit]

Operators[edit]

An operator is any symbol used in an expression used to manipulate data. The seven basic PHP operators are:

  • = (assignment)
  • + (addition)
  • - (subtraction)
  • * (multiplication)
  • / (division)
  • % (modulus)
  • . (concatenation)

In addition, each of the above operators can be combined with an assignment operation, creating the operators below:

  • += (addition assignment)
  • -= (subtraction assignment)
  • *= (multiplication assignment)
  • /= (division assignment)
  • %= (modulus assignment)
  • .= (concatenation assignment)

These operators are used when a variable is added, subtracted, multiplied or divided by a second value and subsequently assigned to itself.

In other words, the statements
$var = $var + 5;

and

$var += 5;
are equivalent.


There are also increment and decrement operators in PHP.

  • ++ (increment)
  • -- (decrement)

These are a special case of the addition and subtraction assignment operators.

This code uses the addition assignment operator to increment and decrement a variable.

Crystal Clear app terminal.png Code:

$var = 0;
 
$var += 1;
echo "The incremented value is $var.\n";
 
$var -= 1;
echo "The decremented value is $var.\n";

Crystal Clear app kscreensaver.png Output:

The incremented value is 1.
The decremented value is 0.

While this is perfectly legal in PHP, it is somewhat lengthy for an operation as common as this. It can easily be replaced by the increment operator, shortening the statement.

This code snippet uses the increment and decrement operators to increase and decrease a variable's value by one.

Crystal Clear app terminal.png Code:

$var = 3;
 
$var++;
echo "The incremented value is $var.\n";
 
$var--;
echo "The decremented value is $var.\n";

Crystal Clear app kscreensaver.png Output:

The incremented value is 4.
The decremented value is 3.
Using the increment operator makes your code slightly easier to read and understand.

For a more in-depth overview of PHP's operators, including an explanation of bitwise operators, refer to the manual link below.

Precedence[edit]

Precedence determines the priority given to certain operators to be performed earlier in a statement. If an operator has higher precedence, it doesn't mean that it is of greater importance; the opposite can often be true.

Associativity

When multiple operators occur that have the same precedence (whether multiple instances of the same operator or just different operators with the same precedence), it becomes important to consider the associativity: whether right (to left), left (to right), or non-associative.

Examples where associativity is irrelevant

In certain cases (as in the example below), especially where the same operator is present, the associativity may make no difference to the result.

The following...

$a = 5*2*3*4; // Equals 120

...with its left associativity is equivalent to:

$a = (((5*2)*3)*4); // Equals 120

However, in this case, right associativity would have produced the same result:

$a = (5*(2*(3*4))); // Would also equal 120
Examples where associativity is relevant in PHP (but not mathematically)

In mathematics, it may be considered irrelevant in which direction a calculation is performed for operators with the same precedence.

For example, the following...

$a = 5+3-2+8; // Equals 14

...is equivalent to this (left associative) statement:

$a = (((5+3)-2)+8); // Equals 14

And, if this were considered according to human conventions in mathematical calculations, the following equivalent right associative expression would produce the same result:

$a = (5+(3+(-2+8))); // Would also equal 14

However, since we are dealing with a linear computer language which doesn't know to convert the "2" into a negative number and group it with the "8" before adding it to the "3" (and then the "5"), if PHP were to perform the following expression in a strict right associative manner, the following (mistaken) outcome would occur:

$a = (5+(3-(2+8))); // Would equal -2

Thus, the associativity is relevant and should be memorized (though it is generally good practice to make one's groupings explicit anyhow—both to avoid mistakes and to improve readability for others looking at the code).

Similar problems occur with multiplication and division. Although with human convention, all adjacent multiplication and division groups would have the multiplication performed at the numerator level and the division at the denominator level, the PHP interpreter does not know to do this, so it is bound to set the left(-to-right) convention when explicit groupings (via parentheses—which have highest precedence) have not been made:

$a = 5 * 4 / 2 * 3; // Equals 30

This is equivalent to the left associative:

$a = (((5 * 4) / 2) * 3); // Also equals 30

However, as with the addition/subtraction example above, performing this by right associativity (in a strictly reverse linear fashion) does not produce the same (intended) result:

$a = (5 * (4 / (2 * 3))); // Equals 3.33333

Newline and Other Special Characters[edit]

Both of the below examples make use of the newline character (\n, \r\n or \r, basing on the OS) to signify the end of the current line and the beginning of a new one.


The newline is used as follows:

Crystal Clear app terminal.png Code:

echo "PHP is cool,\nawesome,\nand great.";

Crystal Clear app kscreensaver.png Output:

PHP is cool,
awesome,
and great.

Notice: the line break occurs in the output wherever the \n occurs in the string in the echo statement. However, a \n does not produce a newline when the HTML document is displayed in a web browser. This is because the PHP engine does not render the script. Instead, the PHP engine outputs HTML code, which is subsequently rendered by the web browser. The linebreak \n in the PHP script becomes HTML whitespace, which is skipped when the web browser renders it (much like the whitespace in a PHP script is skipped when the PHP engine generates HTML). This does not mean that the \n operator is useless; it can be used to add whitespace to your HTML, so if someone views the HTML generated by your PHP script they'll have an easier time reading it.

In order to insert a line-break that will be rendered by a web browser, you must instead use the <br /> tag to break a line.

Notice: The newline is \n for Linux/Unix-based systems, \r\n for Windows and \r for Mac's.

Therefore the statement above would be altered like so:
echo 'PHP is cool,&lt;br /&gt;awesome&lt;br /&gt;and great.';


The function nl2br() is available to automatically convert newlines in a string to <br /> tags.

The string must be passed through the function, and then reassigned:

Crystal Clear app terminal.png PHP Code:

$string = "This\ntext\nbreaks\nlines.";
$string = nl2br($string);
print $string;

Crystal Clear app kscreensaver.png PHP Output:

This<br />
text<br />
breaks<br />
lines.

Crystal 128 yast default.png HTML Render:

This
text
breaks
lines.
Additionally, the PHP output (HTML source code) generated by the above example includes linebreaks.


Other special characters include the ASCII NUL (\0) - used for padding binary files, tab (\t) - used to display a standard tab, and return (\r) - signifying a carriage return. Again, these characters do not change the rendering of your HTML since they add whitespace to the HTML source. In order to have tabs and carriage returns rendered in the final web page, &tab; should be used for tabs and <br /> should be used for a carriage return.

Input to PHP[edit]

PHP has a set of functions that retrieve input. If you are using standard input (such as that from a command-line), it is retrieved using the basic input functions:

Reading from standard input:
$mystring = fgets($stdin);

Or:

$stdin = fopen('php://stdin', 'r'); // opens standard input
$line = fgets($stdin); // reads until user presses ENTER


Web servers[edit]

On web servers, information sent to a PHP app may either be a GET operation or a POST operation.

For a GET operation, the parameters are sent through the address bar. Parameters within the bar may be retrieved by using accessing $_GET['parameter']. On a POST operation, submitted input is accessed by $_POST['parameter'].

A more generic array, $_REQUEST['parameter'] contains the contents of $_GET, $_POST, and $_COOKIE.

For More Information[edit]

Next[edit]

Commenting and Style