Rumah 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 ) 





  

   

Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn

Alat AI Hot

Undresser.AI Undress

Undresser.AI Undress

Apl berkuasa AI untuk mencipta foto bogel yang realistik

AI Clothes Remover

AI Clothes Remover

Alat AI dalam talian untuk mengeluarkan pakaian daripada foto.

Undress AI Tool

Undress AI Tool

Gambar buka pakaian secara percuma

Clothoff.io

Clothoff.io

Penyingkiran pakaian AI

Video Face Swap

Video Face Swap

Tukar muka dalam mana-mana video dengan mudah menggunakan alat tukar muka AI percuma kami!

Alat panas

Notepad++7.3.1

Notepad++7.3.1

Editor kod yang mudah digunakan dan percuma

SublimeText3 versi Cina

SublimeText3 versi Cina

Versi Cina, sangat mudah digunakan

Hantar Studio 13.0.1

Hantar Studio 13.0.1

Persekitaran pembangunan bersepadu PHP yang berkuasa

Dreamweaver CS6

Dreamweaver CS6

Alat pembangunan web visual

SublimeText3 versi Mac

SublimeText3 versi Mac

Perisian penyuntingan kod peringkat Tuhan (SublimeText3)

Panduan Pemasangan dan Naik Taraf PHP 8.4 untuk Ubuntu dan Debian Panduan Pemasangan dan Naik Taraf PHP 8.4 untuk Ubuntu dan Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 membawa beberapa ciri baharu, peningkatan keselamatan dan peningkatan prestasi dengan jumlah penamatan dan penyingkiran ciri yang sihat. Panduan ini menerangkan cara memasang PHP 8.4 atau naik taraf kepada PHP 8.4 pada Ubuntu, Debian, atau terbitan mereka

7 Fungsi PHP Saya Menyesal Saya Tidak Tahu Sebelum ini 7 Fungsi PHP Saya Menyesal Saya Tidak Tahu Sebelum ini Nov 13, 2024 am 09:42 AM

Jika anda seorang pembangun PHP yang berpengalaman, anda mungkin merasakan bahawa anda telah berada di sana dan telah melakukannya. Anda telah membangunkan sejumlah besar aplikasi, menyahpenyahpepijat berjuta-juta baris kod dan mengubah suai sekumpulan skrip untuk mencapai op

Cara Menyediakan Kod Visual Studio (Kod VS) untuk Pembangunan PHP Cara Menyediakan Kod Visual Studio (Kod VS) untuk Pembangunan PHP Dec 20, 2024 am 11:31 AM

Kod Visual Studio, juga dikenali sebagai Kod VS, ialah editor kod sumber percuma — atau persekitaran pembangunan bersepadu (IDE) — tersedia untuk semua sistem pengendalian utama. Dengan koleksi sambungan yang besar untuk banyak bahasa pengaturcaraan, Kod VS boleh menjadi c

Jelaskan JSON Web Tokens (JWT) dan kes penggunaannya dalam PHP API. Jelaskan JSON Web Tokens (JWT) dan kes penggunaannya dalam PHP API. Apr 05, 2025 am 12:04 AM

JWT adalah standard terbuka berdasarkan JSON, yang digunakan untuk menghantar maklumat secara selamat antara pihak, terutamanya untuk pengesahan identiti dan pertukaran maklumat. 1. JWT terdiri daripada tiga bahagian: header, muatan dan tandatangan. 2. Prinsip kerja JWT termasuk tiga langkah: menjana JWT, mengesahkan JWT dan muatan parsing. 3. Apabila menggunakan JWT untuk pengesahan di PHP, JWT boleh dijana dan disahkan, dan peranan pengguna dan maklumat kebenaran boleh dimasukkan dalam penggunaan lanjutan. 4. Kesilapan umum termasuk kegagalan pengesahan tandatangan, tamat tempoh, dan muatan besar. Kemahiran penyahpepijatan termasuk menggunakan alat debugging dan pembalakan. 5. Pengoptimuman prestasi dan amalan terbaik termasuk menggunakan algoritma tandatangan yang sesuai, menetapkan tempoh kesahihan dengan munasabah,

Bagaimana anda menghuraikan dan memproses HTML/XML dalam PHP? Bagaimana anda menghuraikan dan memproses HTML/XML dalam PHP? Feb 07, 2025 am 11:57 AM

Tutorial ini menunjukkan cara memproses dokumen XML dengan cekap menggunakan PHP. XML (bahasa markup extensible) adalah bahasa markup berasaskan teks yang serba boleh yang direka untuk pembacaan manusia dan parsing mesin. Ia biasanya digunakan untuk penyimpanan data

Program PHP untuk mengira vokal dalam rentetan Program PHP untuk mengira vokal dalam rentetan Feb 07, 2025 pm 12:12 PM

Rentetan adalah urutan aksara, termasuk huruf, nombor, dan simbol. Tutorial ini akan mempelajari cara mengira bilangan vokal dalam rentetan yang diberikan dalam PHP menggunakan kaedah yang berbeza. Vokal dalam bahasa Inggeris adalah a, e, i, o, u, dan mereka boleh menjadi huruf besar atau huruf kecil. Apa itu vokal? Vokal adalah watak abjad yang mewakili sebutan tertentu. Terdapat lima vokal dalam bahasa Inggeris, termasuk huruf besar dan huruf kecil: a, e, i, o, u Contoh 1 Input: String = "TutorialSpoint" Output: 6 menjelaskan Vokal dalam rentetan "TutorialSpoint" adalah u, o, i, a, o, i. Terdapat 6 yuan sebanyak 6

Terangkan pengikatan statik lewat dalam php (statik: :). Terangkan pengikatan statik lewat dalam php (statik: :). Apr 03, 2025 am 12:04 AM

Mengikat statik (statik: :) Melaksanakan pengikatan statik lewat (LSB) dalam PHP, yang membolehkan kelas panggilan dirujuk dalam konteks statik dan bukannya menentukan kelas. 1) Proses parsing dilakukan pada masa runtime, 2) Cari kelas panggilan dalam hubungan warisan, 3) ia boleh membawa overhead prestasi.

Apakah kaedah Magic PHP (__construct, __destruct, __call, __get, __set, dll) dan menyediakan kes penggunaan? Apakah kaedah Magic PHP (__construct, __destruct, __call, __get, __set, dll) dan menyediakan kes penggunaan? Apr 03, 2025 am 12:03 AM

Apakah kaedah sihir PHP? Kaedah sihir PHP termasuk: 1. \ _ \ _ Membina, digunakan untuk memulakan objek; 2. \ _ \ _ Destruct, digunakan untuk membersihkan sumber; 3. \ _ \ _ Call, mengendalikan panggilan kaedah yang tidak wujud; 4. \ _ \ _ Mendapatkan, melaksanakan akses atribut dinamik; 5. \ _ \ _ Set, melaksanakan tetapan atribut dinamik. Kaedah ini secara automatik dipanggil dalam situasi tertentu, meningkatkan fleksibiliti dan kecekapan kod.

See all articles