php syntax

 

 

目錄

 


Comment

  • // ...
  • /* .. */

 


require 與 include

 

X_once

  • require_once()
  • include_once()

設定在什麼 relative path include / require

<?php

// 方法1
set_include_path('/usr/lib/pear');

// 方法2
ini_set('include_path', '/usr/lib/pear');

?>

if

<?php
if ($a > $b) {
    echo "a is bigger than b";
} elseif ($a == $b) {
    echo "a is equal to b";
} else {
    echo "a is smaller than b";
}
?>

for 與 foreach

 

for (init counter; test counter; increment counter) {
  code to be executed;
}

i.e.

<?php
for ($x=0; $x<=10; $x++) {
  echo "The number is: $x <br>";
}
?>

foreach ($array as $value) {
  code to be executed;
}

i.e.

<?php
$colors = array("red","green","blue","yellow");

foreach ($colors as $value) {
  echo "$value <br>";
}
?>

 

# key & value

foreach (array_expression as $key => $value)
    statement

 


class

 

Class in same file

<?php
class foo
  {
    function do_foo()
    {
        echo "Doing foo.";
    }
  }

  $bar = new foo;
  $bar->do_foo();
?>

Class in another file

<?php
  require_once('class.php');
  ...
?>

Object in array

Doing print_r() on my array I get the following:

Array (
    [0] =>
        stdClass Object
        (
            [id] => 25
            [time] => 2014-01-16 16:35:17
            [fname] => 4
            [text] => 5
            [url] => 6
        )
)

$array[0]->url   // then access its key

 

 

 

 


Function

 

* Function names are NOT case-sensitive.

function functionName($string) {
  code to be executed;
  return false;
}

 


Heredoc(<<<) - Return a formatted string

 

i.e.

echo <<< EOF
..
...
....
...
..
EOF;

i.e.

# Heredoc text behaves just like a double-quoted string, without the double quotes.
# (Variables are expanded)

<?php
$var = <<<EOD
text goes here
EOD;
?>

要 encode 的字:

\n     linefeed (LF or 0x0A (10) in ASCII)
\r     carriage return (CR or 0x0D (13) in ASCII)
\t     horizontal tab (HT or 0x09 (9) in ASCII)
\v     vertical tab (VT or 0x0B (11) in ASCII) (since PHP 5.2.5)
\e     escape (ESC or 0x1B (27) in ASCII) (since PHP 5.4.0)
\f     form feed (FF or 0x0C (12) in ASCII) (since PHP 5.2.5)
\\     backslash
\$     dollar sign
\"     double-quote

 


var_dump

 

# var_dump — Dumps information about a variable ( includes its type and value)

<?php
  $b = 3.1;
  $c = true;
  var_dump($b, $c);
?>

Dump Client POST Data

# An associative array that by default contains the contents of $_GET, $_POST and $_COOKIE.

var_dump($_REQUEST);

or

var_dump($_POST);

 


newline

 

echo '\r\n';

Only within double quoted strings the escape sequences \r and \n are recognized and replaced by 0x0D and 0x0A respectively, so:

"\r\n"

 


EGPCS Variable

 

GET

<?php
 if (isset($_GET['link'])) {
     echo $_GET['link'];
 }else{
     // Fallback behaviour goes here
 }
?>

# 0 都是 empty !!

if (empty($_GET)) {
    // $_GET is empty
}

Check Number

bool is_numeric ( mixed $var )

EGPCS 的次序

The order in which parameters are taken from the request and the environment is EGPCS
(Environment < GET < POST < Cookies < Built-in variables)

This means that a POST parameter will overwrite the parameters transported on the request line
(GET: QUERY_STRING).

Whitespace at the beginning of parameter names is ignored.

The remaining whitespace (in parameter names) is converted to underscores.
The same applies to dots and to a "["]if the variable name does not contain a matching closing bracket.

When "register_globals" is set to "On" request parameters are automatically converted to script variables.
In some PHP versions it is even possible to override the $GLOBALS array.

PHP will also automatically create nested arrays for you.
For example "p[x][y]=1" results in a total of three variables.

 


Unix time

 

Standard UNIX timestamps are a signed 32bit integer

public int DateTime::getTimestamp ( void )

<?php
  $date = new DateTime();
  echo $date->getTimestamp();
?>

Output:

1414393221

mysql:

mysql data type "timestamp"

0000-00-00 00:00:00

INSERT INTO `edi_record`(`record_time`) VALUES (NOW())

SELECT UNIX_TIMESTAMP( NOW( ) );

1414392987

As for int(10), the (10) portion is merely for display purposes.

 


php import class from another file (include)

 

set_include_path(".:/usr/share/pear:/usr/share/php:" . ROOT . "/pear/:");

require_once('class.php');

 


Array

 

# 沒有 Key

<?php
$array = array("foo", "bar", "hello", "world");
var_dump($array);
?>

# Key

<?php
 $array = array(
    "foo" => "bar",
    "bar" => "foo",
 );
?>

# PHP 5.4 新寫法

<?php
 $array = [
     "foo" => "bar",
     "bar" => "foo",
 ];
?>

 

# Array 的頭尾加減東西

# Pop the element off the end of array

# If array is empty (or is not an array), NULL will be returned.

$stack = array("orange", "banana", "apple", "raspberry");
$fruit = array_pop($stack);

# Push one or more elements onto the end of array

# Returns the new number of elements in the array.

$stack = array("orange", "banana");
array_push($stack, "apple", "raspberry");

# Shift an element off the beginning of array

$stack = array("orange", "banana", "apple", "raspberry");
$fruit = array_shift($stack);

# Prepend one or more elements to the beginning of an array

$queue = array("orange", "banana");
array_unshift($queue, "apple", "raspberry");

 

# Array Size:

$n = sizeof($arrayname);

 

# Delete an element from an array

# unset($array[$index]);
# unset($array["elementName"]);

$x = array("a", "b");
unset($x[0]);

# Array to String

implode — Join array elements with a string

string implode ( array $pieces )
string implode ( string $glue , array $pieces )

glue:

Defaults to an empty string.

$array = array('lastname', 'email', 'phone');
$comma_separated = implode(",", $array);
echo $comma_separated; // lastname,email,phone

 

string to array

array explode ( string $delimiter , string $string [, int $limit ] )

$lines = explode("~", $content);

 

array_merge

$first_array = array(
     'name1' => 'value1',
     'name2' => 'value2',
);
$second_array = array('name3'=>'value3');
$result_array = array_merge((array)$first_array, (array)$second_array);

 


Checking

is_array($var)

 

php check object type: get_class

string get_class ([ object $object = NULL ] )

Returns the name of the class of which object is an instance. Returns FALSE if object is not an object.

If get_class() is called with anything other than an object, an E_WARNING level error is raised.

5.3.0   

NULL became the default value for object, so passing NULL to object now has the same result as not passing any value.

 


String

 

# 移除轉行

$newstr = str_replace('\n', '', $str);
$newstr = str_replace('\r', '', $str);
$newstr = str_replace('\r\n\', '', $str);

OR

$newstr = str_replace(array("\r\n", "\n", "\r"), '', $str);

# 字串長度

int strlen ( string $string )

strrchr()

strrchr(string,char)

The strrchr() function finds the position of the last occurrence of a string within another string,

and returns all characters from this position to the end of the string.

i.e.

// get last directory in $PATH
$dir = substr(strrchr($PATH, ":"), 1);

substr()

substr(string,start,length)

The substr() function returns a part of a string. 由 0 開始.

 


define

 

Usage

define ( string $name , mixed $value [, bool $case_insensitive = FALSE ] ) : bool

global.inc.php

<?php
ini_set("display_errors", "On");
error_reporting(E_ALL);

define(WWWROOT, "/home/vhosts/..."); // cms

會有 Notice

Notice: Use of undefined constant WWWROOT - assumed 'WWWROOT' in /../global.inc.php on line 5

原因

WWWROOT 沒有被 " 包起

Creative Commons license icon Creative Commons license icon