Entry: basic knowledge of PHP programming "array"

Source: Internet
Author: User
The array can be numbered or correlated, that is, the elements of the array can be distinguished to visit PHP based on the number index or normalized string. the array can contain scalar (integer, Boolean, string, floating point number) or composite values (objects or even other arrays), and can contain different types of values

About arrays:

Arrays in PHP are complex and more mobile than arrays in many other advanced languages.

Array is a group of ordered variables, each of which is called an element.

The array can be numbered or correlated, that is, the elements of the array can be distinguished to visit PHP based on the number index or normalized string. the array can contain scalar (integer, Boolean, string, floating point number) or composite values (objects or even other arrays), and can contain different types of values

1. Create an array

PHP provides the array () language structure for creating arrays
$ Numbers = array (5, 4, 3, 2, 1 );
$ Words = array ('web', 'database', 'application ');
Echo $ numbers [2];
Echo $ words [0];
--------------------- Output result ----------------------------------------
3web
---------------------------------------------------------------------
By default, the index of the first element of the array is 0. The values in the array can be retrieved and corrected by applying the square brackets [] syntax.
$ Numbers [5] = 0;
Arrays of digital indexes can create bits starting from any index value.
$ Numbers = array (1 => 'one', 'two', 'Three ', 'Four ');
You can also use loose indexes.
$ Numbers = array (1 => 'one', 3 => 'Three ', 5 => 'zero ');
You can create an empty array by assigning an array () with no parameters to the variable. Then, you can add the value by applying the square brackets [] syntax.
$ Error = array ();
$ Error [] = 'no error !!! ';
$ Error [] = 'second error !!! ';
Echo $ error [0];
Echo $ error [1];
--------------------- Output result ----------------------------------------
No error !!! Second error !!!
---------------------------------------------------------------------

2. join an array

The associative array uses string indexes (or keys) to access values stored in the array.
Arrays of correlated indexes are very useful for database layer interaction.
$ Newarray = array ('first' => 1, 'second' => 2, 'third' => 3 );
Echo $ newarray ['second'];
$ Newarray ['third'] = 5;
Echo $ newarray ['third'];
--------------------- Output result ----------------------------------------
25
---------------------------------------------------------------------

3. heterogeneous array

PHP arrays can contain different types of values

$ MixedBag = array ('cat', 42, 8.5, false );
Var_dump (mixedBag );

4. *** array

Create an array containing arrays. there is no limit on the array dimension, but it is generally hard to imagine an array with more than three dimensions.
$ Planets = array ('mm', 1, 2), array ('nn ', 3, 4), array ('BB', 5, 6), array ('vv ', 7, 8 ));
Print $ planets [2] [0];
$ Planets2 = array ('mm' => array ('a' => 1, 'SS' => 2 ),
'Nn' => array ('DD' => 3, 'ff' => 4 ),
'BB '=> array ('GG' => 6, 'hh '=> 7, 'pp' => array ('Haha !!!! ')),
'Vv '=> array ('JJ' => 6, 'KK '=> 7,'ll' => array ('one', 'two ')));
Print $ planets2 ['vv '] ['ll'] [0];
--------------------- Output result ----------------------------------------
BBone
---------------------------------------------------------------------

5. application loop visit array

There are many ways to traverse arrays (apply the while, for loop) or foreach statements. The easiest way is the foreach statement.
$ Length = array (0,107,202,400,475 );
// Convert centimeter to inch
For ($ I = 0; $ I <5; $ I)
{
Echo ($ length [$ I]/3 );
}
$ J = 0;
While (isset ($ length [$ j])
{
Echo ($ length [$ j]/3 );
$ J;
}
Foreach ($ length as $ cm)
{
Echo ($ cm/3 );
}

--------------------- Output result ----------------------------------------
0
35.6666666667
67.3333333333
133.333333333
158.333333333
0
35.6666666667
67.3333333333
133.333333333
158.333333333
0
35.6666666667
67.3333333333
133.333333333
158.333333333

---------------------------------------------------------------------
Foreach can also iterate the values of associated arrays
$ Sound = array ('cow' => 'moo', 'dog' => 'woof ',
'Pig' => 'Oink ', 'Duck' => 'quack ');
Foreach ($ sound as $ animal => $ noice)
{
Echo '$ animal sounds like this $ noice ......';
}
--------------------- Output result ----------------------------------------
Cow sounds like moo ......
Dog sounds like this: woof ......
Pig sounds like this oink ......
The duck sounds like quack ......

---------------------------------------------------------------------
6. apply the array pointer

Together with the keys and associated values stored in the array, PHP also has an internal index pointing to the current element of the array,
There are several function applications and update the array index to provide access to array elements.
$ A = array ('A', 'B', 'C', 'D', 'e', 'F ');
Echo current ($ );
Each ($ );
Key ($ a); // The pointer to the current array, returns its index
Echo current ($ a); // The value of the current element
Each ($ a); // returns the value of the current element and points the internal Index to the next element.
Each ($ );
Echo current ($ );
Next ($ a); // point to the next element
Echo current ($ );
Prev ($ a); // point to the previous element
Echo current ($ );
End ($ a); // point to the last element
Echo current ($ );
Key ($ );
Echo current ($ );
--------------------- Output result ----------------------------------------
Abdedff
---------------------------------------------------------------------

7. basic array functions

Integer count (mixed var) // returns the number of elements in the array, which can also be used for any variable
Number max (array numbers) // returns the maximum value in the array.
Number min (array numbers) // returns the minimum value in the array.
Boolean in_array (mixed needle, array haystack [, bollean strict]) // you can find the value in the array. The third parameter is optional and the type check is enforced.
Mixed array_search (mixed needle, array haystack [, boolean strict]) // the return key instead of a boolean value,
If no value is found, false is returned. if the element is found to be the first element, 0 is returned, and PHP automatically converts it to false. Therefore, you need to apply ===to determine, as shown below:

$ A = array ('A', 'B', 'C', 'D', 'e', 'F ');
$ Index = array_search ('A', $ );
If ($ index = false)

Echo 'The character 'A' is not invented in array '';
Else
Echo 'index = $ index ';
--------------------- Output result ----------------------------------------
Index = 0
---------------------------------------------------------------------
Array array_reverse (array source [, bool preserve_keys]) // reverse array. a new array is generated. if the optional parameter is true, the association between indexes and elements is retained.
$ A = array ('A', 'B', 'C', 'D', 'e', 'F ');
$ Newa = array_reverse ($ a); // flip directly
Echo $ newa [0];
$ Newb = array_reverse ($ a, true); // The association between indexes and elements is retained.
Echo $ newb [0];
--------------------- Output result ----------------------------------------
Fa
---------------------------------------------------------------------
Sort (array subject [, integer sort_flag]) // sort the elements in ascending order (in the original array)
Rsort (array subject [, integer sort_flag]) // sort the elements in descending order by value (in the original array)
Optional parameters can be specified as SORT_NUMERIC by numeric, SORT_STRING by string, or SORT_REGULAR by common methods.
Sort () and rsort () can be used to associate an array, but the key is lost.
Asort (array subject [, integer sort_flag]) // sort the elements in ascending order of values (in the original array) to maintain key-value Association
Arsort (array subject [, integer sort_flag]) // sort the elements in descending order by value (in the original array) to maintain key-value Association
When asort () arsort () is used for a non-correlated array, the elements are re-arranged in the sorted order, but the index of the visited elements is not changed.
Integer ksort (ayyay subject [, integer sort_flag]) // Sort by key or index in ascending order
Integer krsort (ayyay subject [, integer sort_flag]) // Sort by key or index in descending order
Usort (array subject, string compare_function) // you can define your own sorting rule function based on user-defined sorting, but the function must comply
Uasort (array subject, string compare_function) // integer my_compare_function (mixed a, mixed B), a> B returns 1, a uksort (array subject, string compare_function) // If a is B, 0 is returned.
$ Numbers = array (2,171 );
Sort ($ numbers );
Foreach ($ numbers as $ n)
Echo $ n .'';
$ Numbers = array (2,171 );
Rsort ($ numbers );
Foreach ($ numbers as $ n)
Echo $ n .'';
$ Numbers = array (2,171 );
Sort ($ numbers, SORT_STRING );
Foreach ($ numbers as $ n)
Echo $ n .'';
$ A = array ('O' => 'KK ', 'E' => 'zz', 'Z' => 'HH ', 'A' => 'rr ');
Asort ($ );
Foreach ($ a as $ keyname => $ keyvalue)
Echo $ keyvalue;
$ A = array ('O' => 'KK ', 'E' => 'zz', 'Z' => 'HH ', 'A' => 'rr ');
Ksort ($ );
Foreach ($ a as $ keyname => $ keyvalue)
Echo $ keyvalue;
// Match two strings based on the length
Function cmp_length ($ a, $ B)
{
If (strlen ($ a) <strlen ($ B ))
Return-1;
If (strlen ($ a)> strlen ($ B ))
Return 1;
Return 0;
}
$ Animals = array ('cow', 'ox ', 'monkey', 'mimimi ');
Usort ($ animals, 'cmp _ length ');
Foreach ($ animals as $)
Echo $;
--------------------- Output result ----------------------------------------

 

2 3 5 6 16 19 24 171 171 24 19 16 6 5 3 2 16 171 19 2 24 3 5 6 hhkkrrzzrrzzkkhhoxcowmimonkey
---------------------------------------------------------------------
Array_merge ($ a, $ B) // composite array, I think it is one of the more interesting functions, from two arrays born with an array, with the same key value will be shrouded
/// // Code ////////// //////////////////////////////
$ A = array ('name' => 'hangsan', 10,100 );
$ B = array ('name' => 'lisi', 4,6, 8 );
$ C = array_merge ($ a, $ B );
Var_dump ($ c );
//////////////////////////////////////// //////////////////////////////////
--------------------- Output result ----------------------------------------
Array (6) {['name'] => string (4) 'lisi' [0] => int (10) [1] => int (100) [2] => int (4) [3] => int (6) [4] => int (8 )}
---------------------------------------------------------------------
Array array_combine (array $ a, array $ B) // The value of array a is the key of the new array, and the value of array B is the value of the new array. If the array length is different, false is returned.
/// // Code ////////// //////////////////////////////
$ A = array ('name', 'math', 'China ');
$ B = array ('hangsan );
$ C = array_combine ($ a, $ B );
Var_dump ($ c );
//////////////////////////////////////// //////////////////////////////////
--------------------- Output result ----------------------------------------
Array (3) {['name'] => string (8) 'hangsan' ['math'] => int (4) ['China'] => int (6 )}
---------------------------------------------------------------------

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.