Sie sind auf Seite 1von 21

Comments in PHP PHP echo and print

 A comment in PHP code is a line that is not Statements


executed as a part of the program. Its only
purpose is to be read by someone who is  echo and print are more or less the same.
looking at the code. They are both used to output data to the
screen.
// this is a single-line comment  The differences are small: echo has no
return value while print has a return value
# this is also a single-line comment of 1 so it can be used in
expressions. echo can take multiple
/* parameters (although such usage is rare)
while print can take one argument. echo is
this is a multiple-lines comment
marginally faster than print.
block
that spans over multiple
lines
The PHP echo Statement
*/  The echo statement can be used with or
without parentheses: echo or echo().
// You can also use comments to
leave out parts of a code line
$x = 5 /* + 15 */ + 5; <?php
echo "<h2>PHP is Fun!</h2>";
echo "Hello world!<br>";
echo "I'm about to learn PHP!<br>";
echo "This ", "string ", "was ", "made
", "with multiple parameters.";
?>
The PHP print Statement PHP Integer
 The print statement can be used with or An integer data type is a non-decimal number
without parentheses: print or print(). between -2,147,483,648 and 2,147,483,647.

<?php Rules for integers:


print "<h2>PHP is Fun!</h2>";
 An integer must have at least one digit
print "Hello world!<br>";
 An integer must not have a decimal point
print "I'm about to learn PHP!";  An integer can be either positive or
?> negative
 Integers can be specified in: decimal (base
PHP Data Types 10), hexadecimal (base 16), octal (base
8), or binary (base 2) notation
 Variables can store data of different types,
and different data types can do different In the following example $x is an integer.
things. The PHP var_dump() function returns the
data type and value:
 PHP supports the following data types:
<?php
1. String $x = 5985;
2. Integer var_dump($x);
3. Float (floating point numbers - also called ?>
double)
4. Boolean
5. Array
6. Object
7. NULL
8. Resource
PHP String  Variables can also be emptied by setting
the value to NULL:

 A string is a sequence of characters, like <?php


"Hello world!". $x = "Hello world!";
$x = null;
 A string can be any text inside quotes. You
can use single or double quotes: var_dump($x);
?>
<?php
$x = "Hello world!"; PHP Array
$y = 'Hello world!';
 An array stores multiple values in one
echo $x; single variable.
echo "<br>";
echo $y;  In the following example $cars is an array.
?> The PHP var_dump() function returns the
data type and value:

PHP NULL Value <?php


$cars
 Null is a special data type which can have = array("Volvo","BMW","Toyota");
only one value: NULL. var_dump($cars);
?>
 A variable of data type NULL is a variable
that has no value assigned to it.

 Tip: If a variable is created without a


value, it is automatically assigned a value
of NULL.
PHP Operators
Operators are used to perform operations on Operator Name
variables and values.

PHP divides the operators in the following


+ Addition
groups:

 Arithmetic operators
 Increment/Decrement operators - Subtraction
 Logical operators

PHP Arithmetic Operators * Multiplication

The PHP arithmetic operators are used with


numeric values to perform common arithmetical / Division
operations, such as addition, subtraction,
multiplication etc.
% Modulus

** Exponentiation
PHP Assignment Operators Assignment Same Description
as...
The PHP assignment operators are used with
numeric values to write a value to a variable.

The basic assignment operator in PHP is "=". It x=y x=y The left operand gets set to the
means that the left operand gets set to the value value of the expression on the
right
of the assignment expression on the right.

x += y x=x Addition
+y

x -= y x=x- Subtraction
y

x *= y x=x* Multiplication
y

x /= y x=x/ Division
y

x %= y x=x Modulus
%y
PHP Logical Operators
The PHP logical operators are used to combine
conditional statements.

Operator Name Example Result

and And $x and $y True if both $x and $y are true

or Or $x or $y True if either $x or $y is true

xor Xor $x xor $y True if either $x or $y is true, but


not both

&& And $x && $y True if both $x and $y are true

|| Or $x || $y True if either $x or $y is true

! Not !$x True if $x is not true


PHP Array Operators
The PHP array operators are used to compare
arrays.

Operator Name Example Result

+ Union $x + $y Union of $x and $y

== Equality $x == $y Returns true if $x and $y have the same key/value pairs

=== Identity $x === Returns true if $x and $y have the same key/value pairs in the
$y same order and of the same types

!= Inequality $x != $y Returns true if $x is not equal to $y

<> Inequality $x <> $y Returns true if $x is not equal to $y

!== Non- $x !== $y Returns true if $x is not identical to $y


identity
PHP Increment / Decrement
Operators
The PHP increment operators are used to
increment a variable's value.

The PHP decrement operators are used to


decrement a variable's value.

Operator Name Description

++$x Pre-increment Increments $x by one, then returns $x

$x++ Post-increment Returns $x, then increments $x by one

--$x Pre-decrement Decrements $x by one, then returns $x

$x-- Post-decrement Returns $x, then decrements $x by one


PHP - The if Statement Note: Unlike variables, constants
automatically global across the entire script.
are

The if statement executes some code if one


condition is true.

Syntax Create a PHP Constant


if (condition) {
To create a constant, use the define() function.
code to be executed if condition is
true; define(name, value, case-insensitive)
}
Create a constant with a case-sensitive name:

<?php <?php
$t = date("H"); define("GREETING", "Welcome to
W3Schools.com!");
if ($t < "20") { echo GREETING;
echo "Have a good day!"; ?>
}
?> Create a constant with a case-in
sensitive name:
PHP Constants <?php
A constant is an identifier (name) for a simple
define("GREETING", "Welcome to
value. The value cannot be changed during the W3Schools.com!", true);
script. echo greeting;
?>
A valid constant name starts with a letter or
underscore (no $ sign before the constant
name).
The PHP switch Statement <?php
$favcolor = "red";
Use the switch statement to select one of
many blocks of code to be executed. switch ($favcolor) {
case "red":
Syntax echo "Your favorite color is
red!";
switch (n) { break;
case label1: case "blue":
code to be executed if echo "Your favorite color is
n=label1; blue!";
break; break;
case label2: case "green":
code to be executed if echo "Your favorite color is
n=label2; green!";
break;
break;
default:
case label3: echo "Your favorite color is
code to be executed if neither red, blue, nor green!";
n=label3; }
break; ?>
...
default:
code to be executed if n is
different from all labels;
}
PHP Loops  for - loops through a block of code a
specified number of times

Often when you write code, you want the same for (init counter; test counter;
block of code to run over and over again a certain increment counter) {
number of times. So, instead of adding several code to be executed for each
almost equal code-lines in a script, we can use
iteration;
loops.
}
Loops are used to execute the same block of
code again and again, as long as a certain  foreach - loops through a block of code for
condition is true. each element in an array

In PHP, we have the following loop types: foreach ($array as $value) {


code to be executed;
 while - loops through a block of code as }
long as the specified condition is true

while (condition is true) { PHP String Functions &


}
code to be executed; Numeric/Math Functions
 do...while - loops through a block of code
once, and then repeats the loop as long as
the specified condition is true

do {
code to be executed;
} while (condition is true);
PHP String Functions
The PHP string functions are part of the PHP
core. No installation is required to use these
functions.

strrev() Reverses a string

strlen() Returns the length of a string

strpos() Returns the position of the first occurrence of a string inside


another string (case-sensitive)

str_replace() Replaces some characters in a string (case-sensitive)

strtoupper() Converts a string to uppercase letters


PHP Math Functions
The math functions can handle values within
the range of integer and float types.

intdiv() Performs integer division

abs() Returns the absolute (positive) value of a number

ceil() Rounds a number up to the nearest integer

floor() Rounds a number down to the nearest integer

fmod()
Returns the remainder of x/y
PHP Variables
Rules for PHP variables:

 A variable starts with the $ sign, followed


by the name of the variable
 A variable name must start with a letter or
the underscore character
 A variable name cannot start with a number
 A variable name can only contain alpha-
numeric characters and underscores (A-z,
0-9, and _ )
 Variable names are case-sensitive
($age and $AGE are two different variables)

Remember that PHP variable names are case-


sensitive!

<?php
$txt = "W3Schools.com";
echo "I love $txt!";
?>
PHP Arrays, foreach
command and Array
Functions
A.

array_reverse() Returns an array in the reverse order

array_shift() Removes the first element from an array, and returns the value
of the removed element

array_slice() Returns selected parts of an array

array_search() Searches an array for a given value and returns the key

array_sum() Returns the sum of the values in an array


B.
PHP Global Variables - PHP $GLOBALS
Superglobals $GLOBALS is a PHP super global variable which
is used to access global variables from
Some predefined variables in PHP are anywhere in the PHP script (also from within
"superglobals", which means that they are functions or methods).
always accessible, regardless of scope - and you
can access them from any function, class or file PHP stores all global variables in an array called
without having to do anything special. $GLOBALS[index]. The index holds the name of
the variable.
The PHP superglobal variables are:
The example below shows how to use the super
 $GLOBALS global variable $GLOBALS:
 $_SERVER
 $_REQUEST <?php
 $_POST $x = 75;
 $_GET $y = 25;
 $_FILES
 $_ENV
function addition() {
 $_COOKIE
$GLOBALS['z'] = $GLOBALS['x']
 $_SESSION
+ $GLOBALS['y'];
The next chapters will explain some of the }
superglobals, and the rest will be explained in
later chapters. addition();
echo $z;
?>
PHP $_SERVER PHP $_REQUEST
$_SERVER is a PHP super global variable which PHP $_REQUEST is a PHP super global variable
holds information about headers, paths, and which is used to collect data after submitting an
script locations. HTML form.

The example below shows how to use some of The example below shows a form with an input
the elements in $_SERVER: field and a submit button. When a user submits
the data by clicking on "Submit", the form data
<?php is sent to the file specified in the action attribute
echo $_SERVER['PHP_SELF']; of the <form> tag. In this example, we point to
echo "<br>"; this file itself for processing form data. If you
wish to use another PHP file to process form
echo $_SERVER['SERVER_NAME'];
data, replace that with the filename of your
echo "<br>"; choice. Then, we can use the super global
echo $_SERVER['HTTP_HOST']; variable $_REQUEST to collect the value of the
echo "<br>"; input field:
echo $_SERVER['HTTP_REFERER'];
echo "<br>";
echo $_SERVER['HTTP_USER_AGENT'];
echo "<br>";
echo $_SERVER['SCRIPT_NAME'];
?>
<html>
<body>
PHP $_POST
PHP $_POST is a PHP super global variable
<form method="post" action="<?php echo which is used to collect form data after
$_SERVER['PHP_SELF'];?>"> submitting an HTML form with method="post".
Name: <input type="text" name="fname $_POST is also widely used to pass variables.
"> The example below shows a form with an input
<input type="submit"> field and a submit button. When a user submits
</form> the data by clicking on "Submit", the form data
is sent to the file specified in the action
<?php attribute of the <form> tag. In this example,
we point to the file itself for processing form
if ($_SERVER["REQUEST_METHOD"] data. If you wish to use another PHP file to
== "POST") { process form data, replace that with the
// collect value of input field filename of your choice. Then, we can use the
$name = $_REQUEST['fname']; super global variable $_POST to collect the
if (empty($name)) { value of the input field:
echo "Name is empty";
} else {
echo $name;
}
}
?>

</body>
</html>
<html>
<body>
PHP $_GET
PHP $_GET is a PHP super global variable which
<form method="post" action="<?php echo is used to collect form data after submitting an
$_SERVER['PHP_SELF'];?>"> HTML form with method="get".
Name: <input type="text" name="fname
$_GET can also collect data sent in the URL.
">
<input type="submit"> Assume we have an HTML page that contains a
</form> hyperlink with parameters:

<html>
<?php <body>
if ($_SERVER["REQUEST_METHOD"]
== "POST") { <a
// collect value of input field href="test_get.php?subject=PHP&web=W3schools
$name = $_POST['fname']; .com">Test $GET</a>
if (empty($name)) {
</body>
echo "Name is empty"; </html>
} else {
echo $name; When a user clicks on the link "Test $GET", the
} parameters "subject" and "web" are sent to
} "test_get.php", and you can then access their
values in "test_get.php" with $_GET.
?>
The example below shows the code in
</body> "test_get.php":
</html>
PHP $_COOKIES
Cookies are small text files loaded from a server to a
<html>
client computer storing some information regarding the
<body> client computer, so that when the same page from the
server is visited by the user, necessary information can
<?php be collected from the cookie itself, decreasing the
latency to open the page.
echo "Study " . $_GET['subject'] . "
at " . $_GET['web'];
?>
PHP $_SESSION
Sessions are wonderful ways to pass variables. All you need
</body> to do is start a session by session_start();Then all the
variables you store within a $_SESSION, you can access it
</html> from anywhere on the server. Here is an example:

PHP $_FILES
$_FILES is a super global variable which can be used
to upload files. Here we will see an example in which
our php script checks if the form to upload the file is
being submitted and generates a message if true.

PHP $_ENV
$_ENV is used to return the environment variables from
the web server.

Das könnte Ihnen auch gefallen