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 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 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로 업그레이드하는 방법을 설명합니다.

이전에 몰랐던 후회되는 PHP 함수 7가지 이전에 몰랐던 후회되는 PHP 함수 7가지 Nov 13, 2024 am 09:42 AM

숙련된 PHP 개발자라면 이미 그런 일을 해왔다는 느낌을 받을 것입니다. 귀하는 상당한 수의 애플리케이션을 개발하고, 수백만 줄의 코드를 디버깅하고, 여러 스크립트를 수정하여 작업을 수행했습니다.

PHP 개발을 위해 Visual Studio Code(VS Code)를 설정하는 방법 PHP 개발을 위해 Visual Studio Code(VS Code)를 설정하는 방법 Dec 20, 2024 am 11:31 AM

VS Code라고도 알려진 Visual Studio Code는 모든 주요 운영 체제에서 사용할 수 있는 무료 소스 코드 편집기 또는 통합 개발 환경(IDE)입니다. 다양한 프로그래밍 언어에 대한 대규모 확장 모음을 통해 VS Code는

JWT (JSON Web Tokens) 및 PHP API의 사용 사례를 설명하십시오. JWT (JSON Web Tokens) 및 PHP API의 사용 사례를 설명하십시오. Apr 05, 2025 am 12:04 AM

JWT는 주로 신분증 인증 및 정보 교환을 위해 당사자간에 정보를 안전하게 전송하는 데 사용되는 JSON을 기반으로 한 개방형 표준입니다. 1. JWT는 헤더, 페이로드 및 서명의 세 부분으로 구성됩니다. 2. JWT의 작업 원칙에는 세 가지 단계가 포함됩니다. JWT 생성, JWT 확인 및 Parsing Payload. 3. PHP에서 인증에 JWT를 사용하면 JWT를 생성하고 확인할 수 있으며 사용자 역할 및 권한 정보가 고급 사용에 포함될 수 있습니다. 4. 일반적인 오류에는 서명 검증 실패, 토큰 만료 및 대형 페이로드가 포함됩니다. 디버깅 기술에는 디버깅 도구 및 로깅 사용이 포함됩니다. 5. 성능 최적화 및 모범 사례에는 적절한 시그니처 알고리즘 사용, 타당성 기간 설정 합리적,

PHP에서 HTML/XML을 어떻게 구문 분석하고 처리합니까? PHP에서 HTML/XML을 어떻게 구문 분석하고 처리합니까? Feb 07, 2025 am 11:57 AM

이 튜토리얼은 PHP를 사용하여 XML 문서를 효율적으로 처리하는 방법을 보여줍니다. XML (Extensible Markup Language)은 인간의 가독성과 기계 구문 분석을 위해 설계된 다목적 텍스트 기반 마크 업 언어입니다. 일반적으로 데이터 저장 AN에 사용됩니다

문자열로 모음을 계산하는 PHP 프로그램 문자열로 모음을 계산하는 PHP 프로그램 Feb 07, 2025 pm 12:12 PM

문자열은 문자, 숫자 및 기호를 포함하여 일련의 문자입니다. 이 튜토리얼은 다른 방법을 사용하여 PHP의 주어진 문자열의 모음 수를 계산하는 방법을 배웁니다. 영어의 모음은 A, E, I, O, U이며 대문자 또는 소문자 일 수 있습니다. 모음이란 무엇입니까? 모음은 특정 발음을 나타내는 알파벳 문자입니다. 대문자와 소문자를 포함하여 영어에는 5 개의 모음이 있습니다. a, e, i, o, u 예 1 입력 : String = "Tutorialspoint" 출력 : 6 설명하다 문자열의 "Tutorialspoint"의 모음은 u, o, i, a, o, i입니다. 총 6 개의 위안이 있습니다

PHP에서 늦은 정적 결합을 설명하십시오 (정적 : :). PHP에서 늦은 정적 결합을 설명하십시오 (정적 : :). Apr 03, 2025 am 12:04 AM

정적 바인딩 (정적 : :)는 PHP에서 늦은 정적 바인딩 (LSB)을 구현하여 클래스를 정의하는 대신 정적 컨텍스트에서 호출 클래스를 참조 할 수 있습니다. 1) 구문 분석 프로세스는 런타임에 수행됩니다. 2) 상속 관계에서 통화 클래스를 찾아보십시오. 3) 성능 오버 헤드를 가져올 수 있습니다.

php magic 방법 (__construct, __destruct, __call, __get, __set 등)이란 무엇이며 사용 사례를 제공합니까? php magic 방법 (__construct, __destruct, __call, __get, __set 등)이란 무엇이며 사용 사례를 제공합니까? Apr 03, 2025 am 12:03 AM

PHP의 마법 방법은 무엇입니까? PHP의 마법 방법은 다음과 같습니다. 1. \ _ \ _ Construct, 객체를 초기화하는 데 사용됩니다. 2. \ _ \ _ 파괴, 자원을 정리하는 데 사용됩니다. 3. \ _ \ _ 호출, 존재하지 않는 메소드 호출을 처리하십시오. 4. \ _ \ _ get, 동적 속성 액세스를 구현하십시오. 5. \ _ \ _ Set, 동적 속성 설정을 구현하십시오. 이러한 방법은 특정 상황에서 자동으로 호출되어 코드 유연성과 효율성을 향상시킵니다.

See all articles