Getting Started with PHP

Source: Internet
Author: User
Tags echo command getting started with php html form learn php php script alphanumeric characters

1. The php script can be placed anywhere in the document.

The PHP script begins with <?php and ends with?>.

In PHP, all user-defined functions, classes, and keywords (such as if, else, Echo, and so on) are not case sensitive. All variables are case-sensitive.

2.PHP variables

    • The variable starts with the $ sign, followed by the name of the variable
    • Variable names must begin with a letter or underscore
    • Variable names cannot start with a number
    • Variable names can contain only alphanumeric characters and underscores (A-Z, 0-9, and _)
    • Variable names are case sensitive ($y and $Y are two different variables)

PHP does not have a command to create a variable. Variables are created the first time they are assigned a value.

PHP has three different scope of variables:

    • Local (partial)
    • Global (globally)
    • Static (statically)

Variables declared outside the function have Global scope and can only be accessed outside of the function.

Variables declared inside a function have a local scope and can only be accessed inside the function.

Global scope function MyTest () {  //local scope  echo "<p> variable:</p> inside the test function";  echo "Variable x is: $x";  echo "<br>";  echo "Variable y is: $x";} MyTest (); echo "<p> variable:</p> outside the test function"; echo "variable x is: $x"; echo "<br>" echo "Variable y is: $x";? >

You can create local variables of the same name in different functions, because local variables can only be recognized by the function in which they are created.

The global keyword is used to access variables within the function. To do this, use the Global keyword before (inside the function) variable:

<! DOCTYPE html><?php$x=5;$y=10;function myTest() {   global $x,$y;   $y=$x+$y;} myTest(); // 运行函数echo $y; // 输出变量 $y 的新值?> </body>

PHP also stores all global variables in an array named $GLOBALS [index]. The subscript contains the variable name. This array is also accessible within the function and can be used to update global variables directly.

The above example can be rewritten like this:

<?php$x=5;$y=10;function myTest() {   $GLOBALS[‘y‘]=$GLOBALS[‘x‘]+$GLOBALS[‘y‘];} myTest();echo $y;?>

Typically, all variables are deleted when the function finishes/executes. However, sometimes I need to not delete a local variable. Achieving this requires a bit of further work.

To do this, use the static keyword when you first declare a variable:

<?phpfunction myTest() {   static $x=0;   echo $x;   $x++;}myTest();echo "<br>";myTest();echo "<br>";myTest();echo "<br>";myTest();echo "<br>";myTest();?>  

Then, whenever the function is called, the information stored by the variable is the information contained in the last Call of the function.

Note: The variable is still a local variable of the function.

3.echo & Print

The difference between Echo and print:

    • echo-capable of outputting more than one string
    • Print-only one string is output and always returns 1

Tip: Echo is slightly faster than print because it does not return any values.

1) echo is a language structure that can be used with or without parentheses: Echo or Echo ().

Use the echo command to display strings and variables

<! DOCTYPE html><?php$txt1="Learn PHP";$txt2="W3School.com.cn";$cars=array("Volvo","BMW","SAAB");echo $txt1;echo "<br>";echo "Study PHP at $txt2";echo "<br>";echo "My car is a {$cars[0]}";?> </body>
echo "这段话", "由", "多个", "字符串", "串接而成。";//这段话由多个字符串串接而成。

2) Print is also a language structure and can be used without brackets: print or print ().

<?php$txt1= "Learn PHP"; $txt 2= "W3School.com.cn"; $cars =array ("Volvo", "BMW", "SAAB");p rint $txt 1;print "<br> ";p rint" Study PHP at $txt 2 ";p rint" My car is a {$cars [0]} ";? >

4.PHP Data types

String, integer, floating point, Logic, Array, object, NULL

Var_dump () returns the data type and value of the variable

<?php $cars=array("Volvo","BMW","SAAB");var_dump($cars); ?>

Run Result: Array (3) {[0]=> string (5) "Volvo" [1]=> string (3) "BMW" [2]=> string (4) "SAAB"}

In PHP, you must explicitly declare an object.

First we must declare the class of the object. For this, we use the class keyword. A class is a structure that contains properties and methods.

We then define the data type in the object class, and then use this data type in an instance of the class.

5. String functions

1) strlen () function

Returns the length of a string, measured in characters

2) Strpos () function

Retrieves the specified character or text within a string.

If a match is found, the first matching character position is returned. If no match is found, FALSE is returned.

Echo Strpos ("Hello world!", "World");//6

6.PHP Constants

Valid constant names begin with a character or underscore (there is no $ symbol in front of the constant name). Constants are automatically global throughout the script.

To set a constant, use the Define () function-it uses three parameters:

    1. The first parameter defines the name of the constant
    2. The second parameter defines the value of a constant
    3. The optional third parameter specifies whether the constant name is case-sensitive. The default is False.
Define ("greeting", "Welcome to w3school.com.cn!"); echo greeting;

7. Operators

. String connection. = String Assignment

Output Hello world!
operator name Example Results
and And $x and $y Returns True if both the $x and the $y are true.
Or Or $x or $y Returns true if at least one of the $x and $y is true.
Xor XOR or $x XOR $y Returns True if $x and $y have and only one is true.
&& And $x && $y Returns True if both the $x and the $y are true.
|| Or $x | | $y Returns true if at least one of the $x and $y is true.
! Non - ! $x Returns True if the $x is not true.

operator name example result
+ Union $x + $y Union of $x and $y (but does not overwrite duplicate keys)
= = equal $x = = $y returns True if $x and $y have the same key/value pair.
= = = congruent $x = = = $y returns True if $x and $y have the same key/value pair and the same order type.
! = unequal $x! = $y Returns True if $x is not equal to $y.
<> not Equal $x <> $y Returns True if $x is not equal to $y.
!== not congruent $x!== $y Returns True if the $x is completely different from the $y.
<?php$x = array("a" => "red", "b" => "green"); $y = array("c" => "blue", "d" => "yellow"); $z = $x + $y; // $x 与 $y 的联合var_dump($z);echo "<br>";var_dump($x == $y);echo "<br>";var_dump($x === $y);echo "<br>";var_dump($x != $y);echo "<br>";var_dump($x <> $y);echo "<br>";var_dump($x !== $y);?>   
Array (4) {["a"]=> string (3) "Red" ["B"]=> string (5) "Green" ["C"]=> string (4) "Blue" ["D"]=> string (6) "Yello W "}
BOOL (FALSE)
BOOL (FALSE)
BOOL (TRUE)
BOOL (TRUE)
BOOL (TRUE)

8. Conditional statements

In PHP, we can use the following conditional statements:

    • If statement-executes the code if the specified condition is true
    • If...else Statement-Executes the code if the condition is true, or if the condition is false, executes the other end of the code
    • If...elseif....else statement-Select one of several segment code blocks to execute
    • Switch statement-statement one of several code blocks to execute
switch (expression) {case Label1:  code to is executed if expression = Label1;  break;  Case LABEL2:  code to be executed if expression = Label2;  Break;default:  code to being executed  if expression is different from   both Label1 and Label2;}

9. Cycle

In PHP, we have the following looping statements:

    • While-loop code block whenever the specified condition is true
    • Do...while-Executes the code block first, and then repeats the loop whenever the condition is specified as True
    • For-loop code block specified number of times
    • foreach-iterates through each element in the array and loops the block of code

The Foreach loop applies only to arrays and is used to iterate through each key/value pair in the array. For each iteration of the loop, the value of the current array element is assigned to the $value variable, and the array pointer moves one at a time until the last array element is reached.

<?php $colors = Array ("Red", "green", "blue", "yellow"); foreach ($colors as $value) {  echo "$value <br>";}? >

10. Functions

A user-defined function declaration begins with the closing of a single "function":

function functionname () {  the code being executed;}

Function names can begin with a letter or underscore (not a number). The function name is not sensitive to capitalization.

You can pass information to a function through parameters. Parameters are similar to variables.

Parameters are defined after the function name, inside the parentheses. You can add as many arguments as you want by separating them with commas.

The following example shows how to use the default parameters. If we call the SetHeight () function with no arguments, its parameters will take the default value:

<?phpfunction setHeight($minheight=50) {   echo "高度是:$minheight <br>";}setHeight(350);setHeight();setHeight(135);setHeight(80);?>

To return a value to a function, use the return statement:

<?phpfunction sum ($x, $y) {  $z = $x + $y;  return $z;} echo "5 + 10 =". SUM (5,10). "<br>"; echo "7 + 13 =". SUM (7,13). "<br>"; echo "2 + 4 =". SUM (2,4);? >

11. Arrays

In PHP, the array () function is used to create arrays: Array ();

In PHP, there are three types of arrays:

    • Indexed array-an array with a numeric index
    • Associative array-An array with the specified key
    • Multidimensional arrays-An array that contains one or more arrays

1) There are two methods of creating an indexed array:

Indexes are automatically assigned (index starting from 0):

$cars =array ("Volvo", "BMW", "SAAB");

Or you can manually assign an index:

$cars [0]= "Volvo"; $cars [1]= "BMW"; $cars [2]= "SAAB";

Gets the length of the array-count () function

The count () function returns the length of the array (number of elements), COUNT ($cars)

2) An associative array is an array that uses the specified key that you assign to the array.

There are two ways to create an associative array:

$age =array ("Peter" and "a", "Ben" = "Notoginseng", "Joe" and "43");

Or:

$age [' Peter ']= '; $age [' Ben ']= "Notoginseng"; $age [' Joe ']= "43";

You can then use the specified key in the script:

<?php
$age =array ("Peter" and "a", "Ben" = "Notoginseng", "Joe" and "43");
$len =count ($age);
foreach ($age as $i = = $j) {
echo $i. ': ' $j. ' <br/> ';
}
?>

12. Array sorting

    • Sort ()-sorts an array in ascending order
    • Rsort ()-sorts the array in descending order
    • Asort ()-sorts associative arrays in ascending order based on values
    • Ksort ()-Sorts the associative array in ascending order, based on the key
    • Arsort ()-sorts associative arrays in descending order by value
    • Krsort ()-Sorts the associative array in descending order, based on the key

13. Super Global variables

Many of the predefined variables in PHP are "hyper-global", which means they are available in all scopes of a script. There is no need to perform a global $variable in a function or method; You can access them.

These hyper-global variables are:

    • $GLOBALS
    • $_server
    • $_request
    • $_post
    • $_get
    • $_files
    • $_env
    • $_cookie
    • $_session

1) $GLOBALS-Reference all variables available in the global scope

$GLOBALS This global variable is used anywhere in the PHP script to access global variables (from functions or methods).

PHP stores all global variables in an array named $GLOBALS [index]. The name of the variable is the key of the array.

2) $_server This hyper-global variable holds information about the header, path, and location of the script.

<?php echo $_server[' php_self '];echo "<br>", echo $_server[' server_name '];echo "<br>"; Echo $_server[' Http_host '];echo ' <br> '; Echo $_server[' http_referer '];echo ' <br> '; Echo $_server[' http_user_agent ']; echo "<br>"; Echo $_server[' script_name ');? >

2) PHP $_request is used to collect data submitted by HTML forms.

3) PHP $_post is widely used to collect form data after submitting an HTML form that method= "post". $_post are also commonly used to pass variables.

4) PHP $_get can also be used to collect form data after submitting an HTML form (method= "GET").

$_get can also collect the data sent in the URL.

See: Http://www.w3school.com.cn/php/php_superglobals.asp

The above are derived from W3school http://www.w3school.com.cn/php/index.asp

Getting Started with PHP

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.