Here are some more friendly PHP tutorials.
PHP is a C like language. PHP is called a server side language, because it is executed by a server, never by a browser. The output of the PHP code is sent, as html code, from the server to the browser.
<a href="test.php">Click here. </a>
<form method="POST" action="test.php"> <input type="submit"> </form>
One of the first programs you should run is the following:
<?php phpinfo(); ?>The function phpinfo() tells you which version of PHP you are running, and what it is capable of. The following link gives this information for the PHP build I am currently using.
PHP code can be included anywhere within the html code by placing it inside brackets like these:
<?php ?>
Semicolons MUST go at the end of EACH statement. There is one exception worth noting.
PHP distinguishes between single and double quotes. Material between single quotes is treated literally. If you include variables, you get variable names out. When double quotes are used, variables are evaluated.
<?php // This is a comment. but this is not. /* This is a comment, too. */ ?>
Variable Names:
Variables are created by assigning values to them. The type is determined from the variable assigned. Thus the type of a variable can change in mid program.
Variables can be boolean, integer, float, string, array, or object.
The type of a variable can be determined with the gettype() function.
Constants are declared as follows: define('X', 0);
Constant names are case sensitive. (By convention, they are written in uppercase.) Constant names do not contain a $.
Constants can be boolean, integer, float, or string.
When you need to determine whether a variable has been given a value -- for instance, in checking form input -- the best thing to do is to see php.net's type comparison tables.
gettype()
+ | |
- | |
* | |
/ | |
% | |
++ | increments by 1 |
-- | decrements by 1 |
= | is replaced by |
+= | is increased by |
-= | is decreased by |
*= | is multiplied by |
/= | is divided by |
x%=y | x is replaced by x%y |
The . operator concatenates two strings.
The .= operator works analogously to the += operator.
== | is equal to |
=== | is equal to and has the same type |
!= | is not equal |
> | is greater than |
< | is less than |
>= | is greater than or equal to |
<= | is less than or equal to |
if ( ){ } else{ };
When using if statements, the comparison must be in parentheses. If one statement is used with no curly braces, it must have a semicolon, even if followed by an else. (This differs from most languages.) Curly braces are needed if there is more than one statement. These are not followed by semicolons, when followed by an else.
The key words and and or may be used in PHP. You'll need extra parentheses.
Be sure to use double equals in if statements.
If you use array variables, such as $_POST[v], in if statements, surround them with curly braces to avoid ambiguity.
For loops are just like JavaScript's.
for ($i=0;$i<5;$i++){ statements; };
You can step through arrays using foreach.
foreach($array as $var){ echo($var); }
foreach ($array as $key => $value){ echo"$key $value "; }
while ( ){ };A statement that evaluates to true or false is placed within the parentheses.
The do-while loop is similar:
do { } while ( );
<?php $a=array(key1=>value1,key2=>value2); ?>If the key is omitted, it is by default, 0, 1, 2 etc.
Watch what print_r does with an array.
<?php $a=array('a'=>'apple', 'b' => 'banana', 'c' => array ('x', 'y', z')); print_r ($a); ?>The above example will output:
Array ( [a] => apple [b] => banana [c] => Array ( [0] => x [1] => y [2] => z ) )
To find the number of items in an array, you can use the sizeof function; sizeof() is an alias for count(). You can't use sizeof() on a string. It will return 1.
<?php $a=array('a'=>'apple', 'b' => 'banana', 'c' => array ('x', 'y', z')); $l=sizeof($a) echo"$l"; ?>
Evidently multidimensional arrays are arrays of arrays.
Array elements can be referred to as:
$x[$i][$j]
However, references to multidimensional arrays can be ambiguous. Thus the code:
echo"$x[$i][$j]";
will only yield something such as:
Array[0]
The request was interpreted as a request to echo $x[$i] which is an array, followed by [$j].
To refer to an element of a multidimensional array unambiguously, you can enclose it in curly braces.
echo {$x[$i][$j]};
When strings are placed within double quotes, variables within the string are evaluated.
However, when a string is placed within single quotes, the string is taken literally. Variable names rather than variables are printed out.
String Functions
chr(byte) | Returns the ASCII character of a byte |
ord(char) | Returns the ordinal value of a character |
strlen(string) | Returns length of a string |
trim(string) | removes whitespace from beginning and end of string. Whitespace includes spaces, NULL, tab, new line, vertical tab, and carriage return. |
ltrim(string) | Removes whitespace from beginning of string. |
rtrim(string) | Removes whitespace from end of string. |
substr(string,i,l) | Returns a substring beginning with the ith character.
Set i=0 to start at the beginning of the string. The substring will be l characters long. Omit l to continue to the end of the string. |
str_replace(search,replace,subject) | Replace all instances of "search" with "replace" within the string "subject." |
strpos(string,substring) | Examines string for substring. Returns position or false. |
explode('c', string) | Splits a string into an array. If 'c' is ' ', it will split a sentence into an array of words. |
str_split(string[,n]) | Splits a string into an array of chunks, n characters long. If n is omitted, the string is split into characters. |
number_format(float,n]) | Converts a float to a string with n decimal places. |
The require() function causes the contents of a file to be inserted as that point. The inserted file can be either a PHP file or an html file.
<?php require("test.php"); ?>
<?php require("foot.htm"); ?>
Example:
<?php function state($x){ if ($x=='S') return 'Solid'; else if($x=='L') return 'Liquid'; else if ($x=='G') return 'Gas'; } ?>
Functions can return an array output. The array is declared and filled within the function, and the array variable is returned.
<?php function Colors($h){ $dml=array(3,'dark','medium','light'); return $dml; } ?>
These constants and functions have been available since PHP v 4.
Constants | |
---|---|
M_E | M_PI |
M_EULER | M_SQRTPI |
M_LNPI | M_SQRT2 |
M_LN2 | M_SQRT3 |
M_LN10 |
Arithmetic Functions | |
---|---|
abs(x) | |
max(a,b) | |
min(a,b) | |
round(x) | round to nearest integer |
ceil(x) | round up |
floor(x) | round down |
fmod(a,b) | remainder of the division |
Geometric Functions | |
---|---|
sqrt(x) | square root of x |
pow(x,y) | x to the y |
exp(x) | e to the x |
log(x) | natural log of x |
log10(x) |
Transcendental Functions | |||
---|---|---|---|
sin(x) | asin(x) | sinh() | asinh() |
cos(x) | acos(x) | cosh() | acosh() |
tan(x) | atan(x) | tanh() | atanh() |
Trig Related Functions | |
---|---|
deg2rad() | degrees to radians |
rad2deg() | radians to degrees |
hypot(a,b) | hypotenuse of right triangle of sides a,b |
Integer Conversions | |
---|---|
decbin() | decimal to binary |
dechex() | decimal to hexadecimal |
decoct() | decimal to octal |
hexdec() | hexadecimal to decimal |
octdec() | octal to decimal |
base_convert() |
Random Numbers | |
---|---|
rand(min,max) | Returns a random integer between min and max |
srand() | Seeds the random number generator |
getrandmax() | Returns the maximum random number that can be returned by a call to the rand() function |
lcg_value() | Returns a pseudo random number in the range of (0,1) |
is_finite(x) | true if x is finite |
is_infinite(x) | true if x is infinite |
is_nan(x) | true if x is not a number |
The function scandir('directoryName') returns an array, each term of which consists of one file in the directory.
<?php $directory="/usr/local/"; echo "Contents of Directory $directory<br>"; $folder=scandir($directory); foreach($folder as $var){ echo($var); echo'<br>'; } ?>
Files may be opened and read with the file('filename') function. The result is an array, each item of which corresponds to one line of the file.
<?php echo"Contents of file freetype-config using file() function<br>"; $content=file("/usr/bin/freetype-config"); foreach($content as $var){ echo($var); echo'<br>'; } ?>
The echo statement sends text and html tags to the browser. Echo is not a function. These echo statements are correct:
<?php echo "<h5>One enchanted evening</h5>"; echo $x; echo($x); //When () used, only one variable is accepted. echo $x, $y, $z; //Variables must be sep'd by commas echo $row[0]." ".$row[1]." ".$row[2 ]."<br>"; ?>
If you want to send a quotation mark to the browser, you must send it as \"
The print() function accepts only one argument, and returns true or false.
The print_r() function accepts strings, integers, floats, arrays. If given an array, the keys and values of the array will be printed. One caveat: print_r() will move the array pointer to the end of the array. You can use reset() to bring it back to beginning.
Note: In versions of PHP before 4.0.4, print_r() would continue forever if given an array or object that contains a direct or indirect reference to itself. An example is print_r($GLOBALS).
The functions, printf() and sprintf(), are identical except for one point. The printf() function writes the code to the document, while sprintf() writes it to a string variable.
The first argument of printf() is a string which directs formatting. The succeeding arguments are data to be printed within the string.
The data can be integers, floating point numbers, strings, or boolean variables.
The format string can contain any sort of explanatory text, but the feature which directs formatting is a set of "conversion specifications". We'll call these "specs" for short. There should be one "spec" for each datum.
Each "spec" has two functions:
Each "spec" must have at least two characters: it begins with a % sign and ends with a type specifier. In between may be more characters which further direct the formatting. First let's look at type specifiers, since they are essential.
Type Specifier | Data Type | How Displayed |
---|---|---|
s | string | |
d | integer | as a decimal integer |
b | integer | as a binary integer |
O | integer | as an octal integer |
x | integer | as a hexadecimal integer |
X | integer | as a hexadecimal integer |
u | integer | unsigned integer |
f | floating point | standard decimal notation |
E or e | floating point | scientific notation |
c | byte | ASCII representation |
Need some examples here
try monkeys
octal binary, hex
scientific, decimal
Next let's look at format modifiers, which go between the % and the type specifier. If they are used they must be in the order shown in the table below.
Possible Values | Purpose | Remarks | |
---|---|---|---|
sign | + | Makes a positive number carry a + sign. | Negative numbers carry a sign by default. |
padding | 0, ,'* | specifies the character used for padding, if padding is needed | used only if length specified; default is space |
alignment | - | left justifies | default is right justified |
length | 1,2,3,4,5,6,etc. | minimum number of characters to output | |
precision | .n n=0,1,2,3,etc. | Number of characters after decimal point?? number of decimal digits?? | applies only to floating points |
Example with leading zeros
How to include a % in the format string.
Here output was rounded to 1 decimal point:
$out_bmi=sprintf('%0.1f', $_bmi);
Peter Kantor describes and compares the different PHP output commands in PHP Client Side.
Documentation on sprintf() can be found at php.net
Images and image files can be generated with php. This is explained in the section on PHP Image Functions