顯示廣告
隱藏 ✕
看板 rikaka
作者 rikaka (rikaka)
標題 php array, substr, strpos,callmethod
時間 2012年03月30日 Fri. PM 03:16:30


array
http://php.net/manual/en/language.types.array.php
array(
    key  => value,
    key2 => value2,
    key3 => value3,
    ...
)
array(1, 2) === array(1, 2,)

It is possible to write a comma after last element or omit it. Result is the same, array(1, 2) === array(1, 2,).
Writing comma after last element is useful mainly when formatting array definition on multiple lines


As of PHP 5.4 you can also use the short array syntax, which replaces array() with [].

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

// as of PHP 5.4
$array = [
    "foo" => "bar",
    "bar" => "foo",
;]
?>
The key can either be an integer or a string. The value can be of any type.
string,
float, cast to intergers, means key 8.7 will be stored under 8
bool,cast to integers 1 or 0
Null, cast to empty string
Array and obj: can't be used for keys. resulting in warning:Illegal offset type.

<?php
$array = array(
    1    => "a",
    "1"  => "b",
    1.5  => "c",
    true => "d",
);
var_dump($array);
?>

array(1) {
  [1]=>
  string(1) "d"
}


PHP arrays can contain integer and string keys at the same time 
as PHP does not distinguish between indexed and associative arrays.


<?php
$array = array(
    "foo" => "bar",
    "bar" => "foo",
    100   => -100,
    -100  => 100,
);
var_dump($array);
?>
====>
array(4) {
  ["foo"]=>
  string(3) "bar"
  ["bar"]=>
  string(3) "foo"
  [100]=>
  int(-100)
  [-100]=>
  int(100)
}

The key is optional. If it is not specified, PHP will use the increment of the largest previously used integer key.
有沒有都ok, 如果沒設的話就是用largest previously used int key+1

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

==========>
array(4) {
  [0]=>
  string(3) "foo"
  [1]=>
  string(3) "bar"
  [2]=>
  string(5) "hallo"
  [3]=>
  string(5) "world"
}

It is possible to specify the key only for some elements and leave it out for others:
不全設key也ok

<?php
$array = array(
         "a",
         "b",
    6 => "c",
         "d",
);
var_dump($array);
?>

array(4) {
  [0]=>
  string(1) "a"
  [1]=>
  string(1) "b"
  [6]=>
  string(1) "c"
  [7]=>
  string(1) "d"
}

Array elements can be accessed using the array[key] syntax.

<?php
$array = array(
    "foo" => "bar",
    42    => 24,
    "multi" => array(
         "dimensional" => array(
             "array" => "foo"
         )
    )
);

var_dump($array["foo"]);
var_dump($array[42]);
var_dump($array["multi"]["dimensional"]["array"]);
?>
string(3) "bar"
int(24)
string(3) "foo"


As of PHP 5.4 it is possible to array dereference the result of a function or method call directly.
Before it was only possible using a temporary variable.

Example #7 Array dereferencing
<?php
function getArray() {
    return array(1, 2, 3);
}

// on PHP 5.4
$secondElement = getArray()[1];

// previously
$tmp = getArray();
$secondElement = $tmp[1];

// or
list(, $secondElement) = getArray();
?>


<?php
$arr = array(5 => 1, 12 => 2);//已宣告

$arr[] = 56;    // This is the same as $arr[13] = 56; //新增一個
                // at this point of the script

$arr["x"] = 42; // This adds a new element to //新增一個
                // the array with key "x"
               
unset($arr[5]); // This removes the element from the array

unset($arr);    // This deletes the whole array
?>



Array do's and don'ts

Why is $foo[bar] wrong?

Always use quotes around a string literal array index. For example, $foo['bar'] is correct, while $foo[bar] is not.
But why? It is common to encounter this kind of syntax in old scripts:


<?php
$foo[bar] = 'enemy';
echo $foo[bar];
// etc
?>
This is wrong, but it works.
The reason is that this code has an undefined constant (bar) rather than a string ('bar' - notice the quotes).
PHP may in future define constants which, unfortunately for such code, have the same name.
It works because PHP automatically converts a bare string
(an unquoted string which does not correspond to any known symbol) into a string
which contains the bare string.

For instance, if there is no defined constant named bar, then PHP will substitute in the string 'bar' and use that.
Note: This does not mean to always quote the key.
Do not quote keys which are constants or variables, as this will prevent PHP from interpreting them.



<?php
// Show all errors
error_reporting(E_ALL);

$arr = array('fruit' => 'apple', 'veggie' => 'carrot');

// Correct
print $arr['fruit'];  // apple
print $arr['veggie']; // carrot

// Incorrect.  This works but also throws a PHP error of level E_NOTICE because
// of an undefined constant named fruit
//
// Notice: Use of undefined constant fruit - assumed 'fruit' in...
print $arr[fruit];    // apple

// This defines a constant to demonstrate what's going on.  The value 'veggie'
// is assigned to a constant named fruit.
define('fruit', 'veggie');

// 回顧 $arr = array('fruit' => 'apple', 'veggie' => 'carrot');

// Notice the difference now
print $arr['fruit'];  // apple
print $arr[fruit];    // carrot

// The following is okay, as it's inside a string. Constants are not looked for
// within strings, so no E_NOTICE occurs here
print "Hello $arr[fruit]";      // Hello apple //在"  " 裡面的$arr[frut]是ok的因為" "裡頭是string


// With one exception: braces surrounding arrays within strings allows constants
// to be interpreted

print "Hello {$arr[fruit]}";    // Hello carrot
print "Hello {$arr['fruit']}";  // Hello apple

// This will not work, and will result in a parse error, such as:
// Parse error: parse error, expecting T_STRING' or T_VARIABLE' or T_NUM_STRING'
// This of course applies to using superglobals in strings as well
print "Hello $arr['fruit']";  ""裡面的array['']是不允許的, ""裡面不要加''
print "Hello $_GET['foo']";

// Concatenation is another option
print "Hello " . $arr['fruit']; // Hello apple
?>

------------------
substr
string substr ( string $string , int $start [, int $length ] )

If start is non-negative >=0, the returned string will start at the start'th position in string,
counting from zero. For instance, in the string 'abcdef', the character at position 0 is 'a',
the character at position 2 is 'c', and so forth.

If start is negative<0, the returned string will start at the start'th character from the end of string.

If string is less than or equal to start characters long, FALSE will be returned.

Example #1 Using a negative start
<?php
$rest = substr("abcdef", -1);    // returns "f"
$rest = substr("abcdef", -2);    // returns "ef"
$rest = substr("abcdef", -3, 1); // returns "d"
?>

If length is given and is positive,
the string returned will contain at most length characters beginning from start (depending on the length of string).

If length is given and is negative,
then that many characters will be omitted from the end of string
(after the start position has been calculated when a start is negative).
If start denotes the position of this truncation or beyond, false will be returned.

If length is given and is 0, FALSE or NULL an empty string will be returned.

If length is omitted, the substring starting from start until the end of the string will be returned.

Example #2 Using a negative length
<?php
$rest = substr("abcdef", 0, -1);  // returns "abcde"
$rest = substr("abcdef", 2, -1);  // returns "cde"
$rest = substr("abcdef", 4, -4);  // returns false
$rest = substr("abcdef", -3, -1); // returns "de"
?>
strpos
(PHP 4, PHP 5)

strpos — Find the position of the first occurrence of a substring in a string


 Description

int strpos ( string $haystack , mixed $needle [, int $offset = 0 ] )
Find the numeric position of the first occurrence of needle in the haystack string.


Parameters

haystack
The string to search in.

needle
If needle is not a string, it is converted to an integer and applied as the ordinal value of a character.

offset
If specified, search will start this number of characters counted from the beginning of the string.
Unlike strrpos() and strripos(), the offset cannot be negative.

Return Values

Returns the position of where the needle exists relative to the beginning of the haystack string (independent of offset). Also note that string positions start at 0, and not 1.

Returns FALSE if the needle was not found.

Warning
This function may return Boolean FALSE,
but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.


 Examples

Example #1 Using ===
<?php
$mystring = 'abc';
$findme   = 'a';
$pos = strpos($mystring, $findme);

// Note our use of ===.  Simply == would not work as expected
// because the position of 'a' was the 0th (first) character.
if ($pos === false) {
    echo "The string '$findme' was not found in the string '$mystring'";
} else {
    echo "The string '$findme' was found in the string '$mystring'";
    echo " and exists at position $pos";
}
?>

Example #2 Using !==
<?php
$mystring = 'abc';
$findme   = 'a';
$pos = strpos($mystring, $findme);

// The !== operator can also be used.  Using != would not work as expected
// because the position of 'a' is 0. The statement (0 != false) evaluates
// to false.
if ($pos !== false) {
     echo "The string '$findme' was found in the string '$mystring'";
         echo " and exists at position $pos";
} else {
     echo "The string '$findme' was not found in the string '$mystring'";
}
?>
Example #3 Using an offset
<?php
// We can search for the character, ignoring anything before the offset
$newstring = 'abcdef abcdef'; // 此字串含一個空白space
$pos = strpos($newstring, 'a', 1); // $pos = 7, not 0
?>

Note: This function is binary-safe.

class callmethod

virtual

--
※ 作者: rikaka 時間: 2012-03-30 15:16:30
※ 編輯: rikaka 時間: 2012-04-04 14:54:55
※ 看板: rikaka 文章推薦值: 0 目前人氣: 0 累積人氣: 272 
分享網址: 複製 已複製
guest
x)推文 r)回覆 e)編輯 d)刪除 M)收藏 ^x)轉錄 同主題: =)首篇 [)上篇 ])下篇