首页 php教程 php手册 study note of "Zend PHP 5 Certification Study &

study note of "Zend PHP 5 Certification Study &

Jun 06, 2016 pm 07:54 PM
amp c Note php quot study zend

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 ) 





  

   

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

适用于 Ubuntu 和 Debian 的 PHP 8.4 安装和升级指南 适用于 Ubuntu 和 Debian 的 PHP 8.4 安装和升级指南 Dec 24, 2024 pm 04:42 PM

PHP 8.4 带来了多项新功能、安全性改进和性能改进,同时弃用和删除了大量功能。 本指南介绍了如何在 Ubuntu、Debian 或其衍生版本上安装 PHP 8.4 或升级到 PHP 8.4

我后悔之前不知道的 7 个 PHP 函数 我后悔之前不知道的 7 个 PHP 函数 Nov 13, 2024 am 09:42 AM

如果您是一位经验丰富的 PHP 开发人员,您可能会感觉您已经在那里并且已经完成了。您已经开发了大量的应用程序,调试了数百万行代码,并调整了一堆脚本来实现操作

如何设置 Visual Studio Code (VS Code) 进行 PHP 开发 如何设置 Visual Studio Code (VS Code) 进行 PHP 开发 Dec 20, 2024 am 11:31 AM

Visual Studio Code,也称为 VS Code,是一个免费的源代码编辑器 - 或集成开发环境 (IDE) - 可用于所有主要操作系统。 VS Code 拥有针对多种编程语言的大量扩展,可以轻松编写

在PHP API中说明JSON Web令牌(JWT)及其用例。 在PHP API中说明JSON Web令牌(JWT)及其用例。 Apr 05, 2025 am 12:04 AM

JWT是一种基于JSON的开放标准,用于在各方之间安全地传输信息,主要用于身份验证和信息交换。1.JWT由Header、Payload和Signature三部分组成。2.JWT的工作原理包括生成JWT、验证JWT和解析Payload三个步骤。3.在PHP中使用JWT进行身份验证时,可以生成和验证JWT,并在高级用法中包含用户角色和权限信息。4.常见错误包括签名验证失败、令牌过期和Payload过大,调试技巧包括使用调试工具和日志记录。5.性能优化和最佳实践包括使用合适的签名算法、合理设置有效期、

您如何在PHP中解析和处理HTML/XML? 您如何在PHP中解析和处理HTML/XML? Feb 07, 2025 am 11:57 AM

本教程演示了如何使用PHP有效地处理XML文档。 XML(可扩展的标记语言)是一种用于人类可读性和机器解析的多功能文本标记语言。它通常用于数据存储

php程序在字符串中计数元音 php程序在字符串中计数元音 Feb 07, 2025 pm 12:12 PM

字符串是由字符组成的序列,包括字母、数字和符号。本教程将学习如何使用不同的方法在PHP中计算给定字符串中元音的数量。英语中的元音是a、e、i、o、u,它们可以是大写或小写。 什么是元音? 元音是代表特定语音的字母字符。英语中共有五个元音,包括大写和小写: a, e, i, o, u 示例 1 输入:字符串 = "Tutorialspoint" 输出:6 解释 字符串 "Tutorialspoint" 中的元音是 u、o、i、a、o、i。总共有 6 个元

解释PHP中的晚期静态绑定(静态::)。 解释PHP中的晚期静态绑定(静态::)。 Apr 03, 2025 am 12:04 AM

静态绑定(static::)在PHP中实现晚期静态绑定(LSB),允许在静态上下文中引用调用类而非定义类。1)解析过程在运行时进行,2)在继承关系中向上查找调用类,3)可能带来性能开销。

什么是PHP魔术方法(__ -construct,__destruct,__call,__get,__ set等)并提供用例? 什么是PHP魔术方法(__ -construct,__destruct,__call,__get,__ set等)并提供用例? Apr 03, 2025 am 12:03 AM

PHP的魔法方法有哪些?PHP的魔法方法包括:1.\_\_construct,用于初始化对象;2.\_\_destruct,用于清理资源;3.\_\_call,处理不存在的方法调用;4.\_\_get,实现动态属性访问;5.\_\_set,实现动态属性设置。这些方法在特定情况下自动调用,提升代码的灵活性和效率。

See all articles