Getting Started with PHP

Source: Internet
Author: User
Tags file handling getting started with php

Indexed array Initialization

PHP has two types of arrays: indexed arrays, associative arrays.

Indexes and associations two words are for the keys of an array.

The index array is first introduced, the index array is an array of integers, and the key's integer order starts at 0, and so on.

Here's a diagram to illustrate:

Can be implemented using the following code:

$fruit = array("苹果","香蕉","菠萝");Note that the keys of the array start from 0. You can use print_r($fruit); statements to output array keys and their corresponding values.

Indexed array Assignment

There are three ways to assign an indexed array:

The first is to assign a value with the name of the array variable followed by a square bracket, and of course the key in the index array, in parentheses, must be an integer. Like what$arr[0]=‘苹果‘;

The second is to array() create an empty array, use => symbols to separate the keys and values, the left side represents the key, and the right side represents the value. Of course, in an indexed array, the key must be an integer. Like whatarray(‘0‘=>‘苹果‘);

The third type: Use to array() create an empty array, directly in the array in English single quotation marks or English double quotation marks " , the array will default to establish a 0-based integer key. For example, array(‘苹果‘); this array is equivalentarray(‘0‘=>‘苹果‘);

accessing indexed array Contents

Sometimes we need to take the contents of the array as values out of the What to do? The values in the array are accessed by using the key in parentheses, followed by the name of the array variable.

For example:

$fruit = Array (' Apple ', ' banana '), $fruit 0 = $fruit [' 0 '];p rint_r ($fruit 0);//result for Apple

The function of the above code: first take an array $fruit first value and then assign to a variable $fruit0, the last output variable value.

For iterating through the values in an indexed array

The For loop can access all the values in the array, and below we show the values in the indexed array with a for loop.

For example:

$fruit =array (' Apple ', ' banana ', ' pineapple '); for ($i =0; $i <3; $i + +) {    echo ' <br> array '. $i. ' Value is: '. $fruit [$i];}
foreach iterates through the values in an indexed array

The Foreach loop can access all the values in the array, and we'll use a Foreach loop to iterate through the values in the indexed array.

For example:

$fruit =array (' Apple ', ' banana ', ' pineapple '), foreach ($fruit as $k = + $v) {    echo ' <br> '. $k. ' Value is: '. $v;}
Associative array initialization

Looking back at what was described earlier, PHP has two arrays: an indexed array, an associative array.

Indexes and associations two words are for the keys of an array.

First, the associative array is an array of exponential groups whose keys are strings.

Can be implemented using the following code:

$fruit = Array (    ' apple ' = ' apple ',    ' banana ' and ' banana ',    

You can use print_r($fruit); statements to output array keys and their corresponding values.

Associative array Assignment

There are two ways to assign an associative array:

The first is to assign a value with the name of an array variable followed by a square bracket, of course, the key in the associative array, in parentheses, must be a string. Like what$arr[‘apple‘]=‘苹果‘;

The second is to array() create an empty array, use => symbols to separate the keys and values, the left side represents the key, and the right side represents the value. Of course, the key must be a string in the associative array. Like whatarray(‘apple‘=>‘苹果‘);

accessing associative array contents

Use the name of the array variable followed by the brackets + key to access the values in the array, with the keys enclosed in single or double quotation marks.

Like what:

$fruit [' banana '];p Rint_r ($fruit 0);

The function of the above code: first the value of an array $fruit key to the banana string is taken out and then assigned to a second variable $fruit0, the last output variable value.

The Foreach loop accesses the values in the associative array

The Foreach loop can access all the values in the array, and we'll use a Foreach loop to iterate through the values in the associative array.

For example:

$fruit =array (' apple ' = ' apple ', ' banana ' + ' banana ', ' pineapple ' and ' pineapple '), foreach ($fruit as $k + $v) {    echo ' <br> Fruit's English Key name: '. $k. ', the corresponding value is: '. $v;}
Custom functions

PHP has more than 1000 functions built into it, so the function makes PHP a very powerful language. Most of the time we use the built-in functions of the system to meet the requirements, but the custom function is more clear about the structure and logic of the code by encapsulating a set of code to make it reusable.

How PHP functions are defined:
1. Start with the keyword " function "
2. The function name can begin with a letter or an underscore:function name()
3. Write the function body in curly braces:

Function name () {    echo ' Eric ';}

With the above steps, we define a simple function that, when needed, can be called in the code to call the function name + parameter, for example:name();

Custom functions

PHP has more than 1000 functions built into it, so the function makes PHP a very powerful language. Most of the time we use the built-in functions of the system to meet the requirements, but the custom function is more clear about the structure and logic of the code by encapsulating a set of code to make it reusable.

How PHP functions are defined:
1. Start with the keyword " function "
2. The function name can begin with a letter or an underscore:function name()
3. Write the function body in curly braces:

Function name () {    echo ' Eric ';}

With the above steps, we define a simple function that, when needed, can be called in the code to call the function name + parameter, for example:name();

Parameters of the function

PHP functions can have no parameters, there can be several parameters, multiple parameters are called parameter lists, separated by commas, the parameters are similar to a variable, called to pass data into the function body. By passing parameters, we can make the function implement the operation of the parameters and get the result we want.

The variable name of the parameter can be freely specified, but it is best to be able to express the relevant meaning, commonly used to set the parameters of the method:

function sum ($a, $b) {     return $a + $b;}
return value

Use the return keyword to return a value to a function that returns any type that includes an array and an object, or NULL if the return is omitted.

function Add ($a) {    return $a +1;} $b = Add (1);

The return statement immediately aborts the function and returns control back to the line of code that called the function, so the return value of the following function is the same as the function above.

function Add ($a) {    return $a +1;    $a = ten;    return $a +20;} $b = Add (1);

A function cannot return multiple values, but you can get a similar effect by returning an array.

function numbers () {    return Array (1, 2, 3);} List ($one, $two, $three) = numbers ();
Variable functions

The so-called mutable function, that is, the function is called by the value of the variable, because the value of the variable is variable, so you can call different functions by changing the value of a variable. Often used in callback functions, function lists, or depending on dynamic parameters to invoke different functions. The variable function is called by the variable name in parentheses.

Function name () {    echo ' Jobs ';} $func = ' name '; $func (); Calling a mutable function

Mutable functions can also be used on the object's method calls.

Class Book {    function GetName () {        return ' bookname ';    }} $func = ' GetName '; $book = new book (); $book-$func ();
Built-in functions

Built-in functions refer to PHP's default supported functions, and PHP contains a number of standard common processing functions, including string processing, array functions, file handling, session and cookie processing.

We first take the string processing function as an example, through the built-in function str_replace can implement the substitution of strings. The following example replaces "Jobs" with "Steven Jobs":

$str = ' I am jobs '; $str = str_replace (' Jobs ', ' Steven Jobs ', $STR); Echo $str; The result is "I am Steven Jobs"

Other functions are supported by other extensions, such as MySQL database processing functions, GD image processing functions, mail processing functions, PHP default loading some of the common extension libraries, we can install or load other extension libraries to increase the PHP processing function.

We'll cover more of the other built-in functions and usage in the later chapters.

Determine if a function exists

When we create custom functions and understand the use of mutable functions, in order to ensure that the functions called by the program are present, we often use function_exists to determine whether a function exists. The same method_exists can be used to detect whether a class's methods exist.

function func () {}if (function_exists (' func ')) {    echo ' exists ';}

class defines whether the class_exists can be used.

Class myclass{}//checks for the existence of an if (class_exists (' MyClass ')) {    $myclass = new MyClass () before use;}

There are many such checks in PHP, such as whether a file exists file_exists, and so on.

$filename = ' Test.txt ', if (!file_exists ($filename)) {    echo $filename. ' Not exists. ';}
Classes and objects

Class is the basic concept of object-oriented programming, popular understanding of the class is the reality of a certain kind of things abstract, such as cars can be abstracted as a class, the car has a name, tires, speed, weight and other properties, can have shift, forward, backward and other operating methods.

A typical method for defining a car class is:

Class Car {    $name = ' car ';    function GetName () {        return $this->name;    }}

A class is a structural description of something, and an object is a concrete example of something, such as a car, which can be understood as the general class of a car, but the car is a specific car object.

object is instantiated with the New keyword:

$car = new car (); Echo $car->getname ();

Classes are similar to objects, but there are essentially differences, classes are abstract concepts, and objects are concrete instances. Class can make a program reusable.

Create an Object

In the previous section, we used car examples to understand classes and objects, and in this section we'll look at the definition methods for classes, which start with the keyword class, then the class name and curly braces, and define the properties and methods of the class in curly braces. The class name must be a letter or an underscore, followed by a number of letters, numbers, or underscores, the class name is best to be ideographic, you can use nouns or English words.

Define a class Car {    //define a property public    $name = ' car ';    Definition method Public    function GetName () {        ///method can use $this pseudo-variable to call the object's property or method        return $this->name;    }}

To create an instance of a class, you can create an object using the New keyword.

$car = new car ();//You can also use variables to create $classname = ' car '; $car = new $className ();

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.