Home > php教程 > php手册 > body text

study note of "Zend PHP 5 Certification Study &

WBOY
Release: 2016-06-06 19:54:21
Original
1048 people have browsed it

study note of Zend PHP 5 Certification Study --array author: jeff_zeng date:2009.12.22 Email:zengjiansheng1@126.com QQ:190678908 MSN:zengjiansheng1@hotmail.com Blog:http://blog.csdn.net/newjueqi 1. what is array? All arrays are ordered col

study note of >--array

author: jeff_zeng
date:2009.12.22
Email:zengjiansheng1@126.com

QQ:190678908
MSN:zengjiansheng1@hotmail.com

Blog:http://blog.csdn.net/newjueqi


1. what is array?
  All arrays are ordered  collections of the items, called elements.Each element is identified by a key that is unique to
the array which belongs to. Keys can be either Intger or the string with no limited length.

2.array created one of the two ways

a, use the function array()

for example:

$myarray=array(1,4,5);

echo $myarray[0].'
'; //output "1"
echo $myarray[1].'
';//output "4"
echo $myarray[2].'
';//output "5"

 $myarray=array('one'=>'it is one','two'=>'it is

two','three'=>'it is three');
 echo $myarray['one'].'
'; //output "it is one"
echo $myarray['two'].'
';//output "it is two"
echo $myarray['three'].'
';//output "it is three"

 $myarray=array(5=>1,4=>2,3=>9);

echo $myarray[5].'
'; //output "1"
echo $myarray[4].'
';//output "2"
echo $myarray[3].'
';//output "9"
echo $myarray[1].'
';//output nothing
//so we can see that the array index can start with random   Integer

b,the second way of accessing the arrays is by means of the array operator([]):

for example:
$myarray[]=3;
$myarray[]=4;
$myarray[5]=7;

echo $myarray[0].'
'; //output "3"
echo $myarray[1].'
';//output "4",note, it is not output "3"
echo $myarray[2].'
'; //output nothing
echo $myarray[5].'
';//output "7"

$myarray[1]=10;
echo $myarray[1].'
';//output "10"

  From this example we can guest that the array may be has a point which point to  current index.

3.printing arrays

There are three ways to print array

a, echo

   Echo can be used to output the value of an expression-include the single variable.While echo is extremely useful ,
it exhibits some limitations that curb it helpfulness in certain situaction,for example ,while debug a script ,one
often need to output the value of the expression ,but also the type of the expression.Another problem is that echo can deal
with the composite data type like arrays and objects.

b, print_f()
  It can print out the content of composite value, and it can output it as string.

for example:

$myarray["my"]=10;
$myarray[]=3;
$myarray[]=4;
$myarray[5]="34";

print_r($myarray);

Output:
Array ( [my] => 10 [0] => 3 [1] => 4 [5] => 34 )

c,var_dump()


   It can print out the data type and the length of  each value.

for example:

$myarray["my"]=10;
$myarray[]=3;
$myarray[]=4;
$myarray[5]="34";

var_dump($myarray);

Output:
array(4) { ["my"]=> int(10) [0]=> int(3) [1]=> int(4) [5]=>

string(2) "34" }

4.the Index of array

   When a element is added to the array without specifying a key, PHP would automatical assign a numeric one that is the
greatest numeric key already in existence in the array.

for example:

$myarray=array(3=>5);
$myarray[]=6;
echo $myarray[3].'
'; //output "5"
echo $myarray[4].'
';//output "6"

  Note that it is true even the array contain a mix of numeric and string value.

for example:
$myarray=array(3=>5,'name'=>'tom');
$myarray[]=6;
echo $myarray[3].'
'; //output "5"
echo $myarray[4].'
';//output "6"

5.List() function

  Sometimes it simple to work with the values of the arrayes by assign them into different variables, PHP provider a function list().
 
6.Array Operations

  A number of operators behave differently if the operands are arrays .The addition operator + can be used to create the union
of its two operands:

for example:

$a=array(1=>6,2=>7,3=>5,'d'=>5);
$b=array(3=>10,4=>13,'d'=>3,5=>34 );
print_r($a+$b);

//Output:
Array ( [1] => 6 [2] => 7 [3] => 5 [d] => 5 [4] => 13 [5] => 34

)

From the Output Result we can see that :
1.The result array has all of the elements of the two orginal arrays.
2.If two arrays have a same key(even have different value), the result of the array will appereace only one key which come from
the first array.
3.The result array orderes first show the $a, and not the same .

key of $a which in $b.

7.Comparing Arrays
  We can performed using the equivalence and identity operators to array_to_array comparison .

for example:
$a=array(1,2,3);
$b=array('1'=>2,'0'=>1,'2'=>3);
$c=array('b'=>2,'a'=>1,'c'=>3);

var_dump( $a==$b);
var_dump( $a===$b);
var_dump( $a==$c);
var_dump( $a===$c);

//Output
bool(true) bool(false) bool(false) bool(false)

a question in this program:
var_dump( $a==$c); //the computer output false, but in the

> it is true.



From the result of output , we can know that :
1.The equivalence operator '==' return true if both arrays have the number of the elements with the values and keys , regardless of their order.
2.The identity operator '===' return ture  if the array contains same key/value pairs in the same order.


8.count ,search and delete elements

  The size of the array can be retrieved by call the count() function.

for example:
$a=array(1,2,3);
$b=array();
$c=20;

echo count($a);//Output 3
echo count($b);//Output 0
echo count($c);//Output 1

  We can see from the output , count() can't used to determine whether a variable contains an array, we can use is_array() instead.

   isset() has a drawback of considering an element whose value is NULL--which is perfectly valid.

for example:
    
    $a=array('a'=>NULL,'b'=>'2');
    echo isset( $a['a']); //output null

  The correct way to determine whether a array element  exist  is to use array_key_exists() instead:
 
for example:
$a=array('a'=>NULL,'b'=>'2');
echo array_key_exists( 'a',$a); //output 1

   If want to determine whether an element with a given value exist in an arry, we can use in_array()

for example :
$a=array('a'=>NULL,'b'=>2);
echo in_array( 2,$a ); //output true

   Finally , an element can be deleted from an array by unsetting it :

for example:

$a=array('a'=>1,'b'=>2);
unset($a['a']);
print_r($a); //output Array ( [b] => 2 )

9. Flipping and Reversing

a, array_flip()

  Inverts the value of each element of an array with its key

for example:

$a=array(1,2,'a');
var_dump( $a ); //output:array(3) { [0]=> int(1) [1]=> int(2) [2]=> string(1) "a" }
var_dump( array_flip($a));//output:array(3) { [1]=> int(0) [2]=> int(1) ["a"]=> int(2) }

b, array_reverse()

  Invert the order of the array's element

for example:

$b=array(1,2,'a');
var_dump( array_reverse($b));//output array(3) { [0]=> string(1) "a" [1]=> int(2) [2]=> int(1) }

10. The array pointer

  We can created a function that output all the value in the array.
  First , we use reset() to rewind the internal array pointer .
  Next , we use while loop the array ,we output the current key and value by using key() and current().
  Finally, we advance the array pointer ,using next(). The loop continutes until we no longer hava a valid key.

for example:

$a=array(2,'ehllo',3,4);
reset($a);
while( key($a)!==NULL )
{
    echo "
";
    echo key($a).': '.current($a).PHP_EOL;
    next($a);
}


11. the easy way of iteratoring array

   PHP provides a function foreach() to iterator from start to finish.

for example:
$a=array(1,2,3,4);
foreach ( $a as $value )
{
    echo $value."  ";
    $value=$value+1; //output:1 2 3 4
}
echo "
";
foreach ( $a as $value )
{
    echo $value."  ";//output:1 2 3 4
}


  Note that the foreach() function uses the copy of the array itself ,so the changes made into the array are
not reflected in the iteration.

  PHP5 also introduced the possibility of modifying the content of array directly by assigning the value of
each element to the variable by reference rather than by value.

for example:
$a=array(1,2,3,4);
foreach ( $a as $key=>&$value )
{
    echo $value."  ";
    $value+=1; //output:1 2 3 4
}
echo "
";
foreach ( $a as $desValue )
{
    echo $desValue."  ";//output:2 3 4 5  
}


Note that the foreach() will be very danger show times, look at this example:
$a=array(1,2,3,4);
foreach ( $a as $key=>&$value )
{
}
echo "
";
foreach ( $a as $value )
{
    echo "
";
}
print_r($a);


  It natrual to think that this srcipt do nothing to the array, it will not affects its contents.But the reslut
is follow:
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 3 )

   As you can see. The content hased been changed,the last key now contain the value "3", the original value
should be 4.
   So, what would this happen?
   Here is what is going on. The first foreach loop do nothing to the array,  it does casue $value to be
assigned a reference to each of $a element,so by the time of the foreach over, $value , a reference to $a[3].
   Now we add a output expression to show what happen in the second foreach loop:
   the code as follow:

$a=array(1,2,3,4);
foreach ( $a as $key=>&$value )
{
}
echo "
";
foreach ( $a as $value )
{
    print_r($a);
    echo "
";
}

//output result:
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 1 )
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 2 )
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 3 )
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 3 )

12.Passive Iteration

  The array_walk function can be used to perform an iteration of an array in which a used-
defined function is called.

for example:
function changeNum(&$value, &$key)
{
     $value=$value+1;
     echo $key."
";
}

$a=array('a'=>1,'b'=>2,'c'=>3);
array_walk($a, changeNum);
print_r($a);

//output
a
b
c
Array ( [a] => 2 [b] => 3 [c] => 4 )

another example:

function addChar(  &$value, &$key )
{
    $key=$key.'a';
}

$a=array('a','b');
$b[]=array('11','22','33');
$b[]=array('44','55');

$map=array_combine($a,$b);

array_walk_recursive( $map,addChar );

//output:
Array ( [a] => Array ( [0] => 11 [1] => 22 [2] => 33 ) [b] => Array ( [0] => 44 [1] => 55 )

)

  The function array_walk_recursive() example:
function addChar(  &$value, &$key )
{
    echo $key.' hold '.$value.'
';
}

$a=array('a' => 'apple', 'b' => 'banana');
$b=array('sweet' => $a, 'sour' => 'lemon');

array_walk_recursive($b,addChar);

//output:
a hold apple
b hold banana
sour hold lemon

13.Sorting array

  There are total of 11 functions in the PHP core whose only goal is to privode the various
methods of sorting the content of an array.
   Sort()  sorts an array based on its value.

for example:

$a=array('a'=>'bar','b'=>'bas','c'=>'apple');
sort($a);
print_r($a); //output:Array ( [0] => apple [1] => bar [2] => bas )


  As you can see, the sort function modifies the actual array it is privided.
  Thus, sort() destroies the all the keys in the array and renumberes it's element starting
from zero.If you want to maintain the key association , you can use asort().

for example:
$a=array('a'=>'bar','b'=>'bas','c'=>'apple');
asort($a);
print_r($a); //output:Array ( [c] => apple [a] => bar [b] => bas )

  Both sort() and asort() accept a second,optional parameter that allows you to specify how
the sort operation takes place:

SORT_REGULAR:Compare items as they appear in the array, without performing any kind of the
conversion.This is the default behaviour.

SORT_NUMERIC: Convert each element to a numeric value for sorting purposes.

SORT_STRING: Comparing all elements as strings.

Note: Both the sort() and asort() sort value in ascending order. To sort them in descending
order , you can use rsort() and arsort().

  If you want to maintain all the key-value assication , you can use natsort().

for example:
$a=array('1a','2a','10a');
natsort($a);
print_r($a);//output:Array ( [0] => 1a [1] => 2a [2] => 10a )


14. Other sort

  In addition to the sort function we have seen this far, PHP allows you to sort the array
by key(rather than by value),using the ksort(), krsort().

for example:
$a=array(2=>'a',1=>'b',3=>'c');
ksort($a);
print_r( $a );//output:Array ( [1] => b [2] => a [3] => c )

   And we can sort the array by providing a user-defined function().
   
for example:
/**
 * sort according to the length of the value
 * if the length is the same, sort normally

 */
function getSort( $left, $right )
{
    $flag=strlen($left)-strlen($right);
    if( $flag==0 )
    {
        return 0;
        
    }
    else{
        return $flag;
    }
}

$a=array('1333a','2a','10a');
usort($a,getSort);
print_r($a);//output:Array ( [0] => 2a [1] => 10a [2] => 1333a )

  This script allow us to sort the array by a rather complication set of rules.First, we sort according to the length of  each element's string representation.Elements whose values have the same length are sorted using regular string compresion rules; out user-defined function must ruturn a value of zero if the two values are to be considered equal, a value less than zero if the left-hand value is lower than the right-hand one , and a positive number otherwise.

  As we can see, usort() lost all the key-value association and renumbered our array. This can be valided by using uasort().You can even sort by key by using uksort().

15. The anti-sort

  There is circumstance where, instead of sorting the keys, you want to scramble the contents so that the keys are randomized, this can be done by using the shuffle() function.

for example:
$a=array(1,2,3,4);
shuffle($a);
print_r($a);//output:Array ( [0] => 2 [1] => 1 [2] => 4 [3] =>

3 )

  As you can see, the key-value association is lose,however, this problem is easily overcome by using anohter function array_keys(), whick return a array whose values are the keys of the array passed to it.

for example:
$a=array('a'=>1,'b'=>2,'c'=>3,'d'=>4);
$key=array_keys($a);
shuffle($key);
foreach ( $key as $value){
    echo $value. "--". $a[$value]."
";
}

//output:
b--2
c--3
a--1
d--4

  If you want to extract an individual element from the array, this can be done by using array_rand(), which return one or more random key from the array.

for example:
$a=array('a'=>1,'b'=>2,'c'=>3,'d'=>4);
$key=array_rand($a);
print_r($key);//output:a
print_r($a);//output:Array ( [a] => 1 [b] => 2 [c] => 3 [d] =>

4 )

  As you can see,  extracting the key from the array doen't remove the correspending element from it.

16. Arrays as Stacks, Queues, Sets

   Arrays are often be used  as Stack, Queue. PHP simplies this approach by prividing a set of functions can be push and pop(for Stack) and shirt and unshirt(for Queue) element from an array.

   First, we take a loot at the Stacks:
$a=array(1,2,3);
array_push($a,5,6,7);
print_r($a);//output:Array ( [0] => 1 [1] => 2 [2] => 3 [3] =>

5 [4] => 6 [5] => 7 )
array_pop($a);
print_r($a); //output:Array ( [0] => 1 [1] => 2 [2] => 3 [3]

=> 5 [4] => 6 )

  In this example, we first create an array, and we add two elements to it using array_push().Next , using array_pop(), we extract the last element added to the array.
  Note:As you have probably noticed, when only one value if being pushed, array_push() is equivalent to adding an element to an array using syntax $a[]=$value, in fact, the latter is much faster, since no function call takes place and, therefore, should be the preferred approach unless you need to add more than one value.

  If you intend to use array as queue, you can add elements to the beginning and extract them from the end by using array_unshift() and array_shift().

for example:
$a=array(1,2,3);
array_shift($a);
print_r($a);//output Array ( [0] => 2 [1] => 3 )
array_unshift($a,4,5);
print_r($a);//output Array ( [0] => 4 [1] => 5 [2] => 2 [3] =>

3 )


  In the example, we use array_shift() to put the frist element out of the array, and use array_unshift() to add a element to the beginning of the array.
  Note that the value order of array after adding a element to the array.
  Most php function are designed to perform set operation on array.For example, the function array_diff() are used to compute between two arrays.

for example:
$a=array(1,2,3);
$b=array(1,4,3);
print_r(array_diff($a,$b));//output:Array ( [1] => 2 )

  The call to array_diff() in the code above will caugth all the values of $a that also appeared in $b to be retained,while everything else is discarded.
  If you want to the difference to be compute based on key-value pairs, you will have to use array_diff_assoc() instead.Whereas you want it to be computed on key alone, the function array_diff_key() will this trick.Both of two functions have the user-defined callback function versions called   
array_diff_uassoc() and array_diff_ukey() respectively.
  Conversely to the array_diff(), array_intersect() will compute the interdiv between two arrays.

for example:
$a=array(1,2,3);
$b=array(1,4,3);
print_r(array_intersect($a,$b));//output:Array ( [0] => 1 [2] => 3 ) 





  

   

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template