search
HomeBackend DevelopmentPHP TutorialPHP Study Notes: Array_PHP Tutorial

PHP Study Notes: Array_PHP Tutorial

Jul 21, 2016 pm 03:27 PM
phponeunderhostcreateexisthowstudydefinitionusarrayWaynotes

1. How to define an array: There are two main ways to create an array in PHP. Let’s take a look at how to create an array

(1) Create an array by directly assigning a value to each element.

The format is: $arrayname[key]=value;

where arrayname is the name of the array, key is the key of the array element, and value is the value of the element. The key can be a number such as 0, 1, 2, or 3, or a string. As shown below:

Copy code The code is as follows:

1 2 //Use 1, The values ​​​​of 2 and 3 are used as the keys of the array
3 echo '

The key value of array $array1 is:

';
4 $array1[1]='a';
5 $array1[2]='b';
6 $array1[3]='c';
7 print_r($array1);
8
9 //If the key is omitted method, the default key of the array is a value that increases from 0
10 echo '

The key value of array $array2 is:

';
11 $array2[]='a ';
12 $array2[]='b';
13 $array2[]='c';
14 print_r($array2);
15
16 //With characters String as the key of the array
17 echo '

The key value of array $array3 is:

';
18 $array3['one']='a';
19 $array3['two']='b';
20 $array3['three']='c';
21 print_r($array3);
22 ?>

The output result of the above code is:

The key value of array $array1 is:

Array ( [1] => a [2] => b [3] => c )
The key value of array $array2 is:

Array ( [0] => a [1] => b [2] => c )
Array The key value of $array3 is:

Array ( [one] => a [two] => b [three] => c )

(2) Use the array function directly Define an array.

The format is: $arrayname=array (key1=>value1, key2=>value2);

where arrayname is the name of the array, key1 and key2 are the keys of the array, and value1 and value2 correspond respectively. The values ​​of key1 and key2.

Give an example, such as the following code:
Copy code The code is as follows:

1 php
2 //Use numerical values ​​as keys
3 $array6=array(1=>'a',2=>'b',3=>'c');
4 echo '

The keys and values ​​of array $array6 are:

';
5 print_r($array6);
6 //Use string as key
7 $array7=array ('one'=>'a','two'=>'b','three'=>'c');
8 echo '

The keys and values ​​of array $array7 are :

';
9 print_r($array7);
10 //How to omit the key
11 $array8=array('a','b','c');
12 echo '

The keys and values ​​of array $array8 are:

';
13 print_r($array8);
14 ?>

The result is:

The keys and values ​​of array $array6 are:

Array ( [1] => a [2] => b [3] => c )
The keys and values ​​of array $array7 are:

Array ( [one] => a [two] => b [three] => c )
The keys of array $array8 The keys and values ​​are:

Array ( [0] => a [1] => b [2] => c )

Note:

1 >If you specify a value as the key for an element in the array, the default key of all elements after this element is the self-increasing, non-repeating value of the specified value.

It’s a bit difficult to understand simply by looking at the literal meaning. Let’s take a look at an example:

The following code:
Copy code The code is as follows:

1 2 //The key of the first element of array $array4 is specified as 2, and the keys of the subsequent 2nd and 3rd elements are omitted. Method
3 $array4[2]='a';
4 $array4[]='b';
5 $array4[]='c';
6 //The 4th The key of the element is explicitly specified as 10, and the keys of the subsequent 5th and 6th elements are omitted
7 $array4[10]='d';
8 $array4[]='e';
9 $array4[]='f';
10 //The key of the 7th element is specified as 9, and the keys of the subsequent 8th and 9th elements are omitted
11 $array4[9] ='g';
12 $array4[]='h';
13 $array4[]='i';
14 //Print the keys and values ​​of the array
15 print_r($ array4);
16 ?>

The result is:

Array ( [2] => スa [3] => b [4] => c [10] => d [11] => スe [12] => f [9] => g [13] => ス [14] => ス )

Explanation: The key of the seventh element is 9. Under normal circumstances, the key The eight elements should be 10, but keys 10, 11 and 12 have been used by elements before, so the key of the eighth element is 13.

2> Whether a number or a string is used as the key of an array element, it only represents the key of this element and has no direct relationship with the position of this element in the array. This is related to C# The biggest difference between arrays in other languages. Here's an example.

The following code:
Copy the code The code is as follows:

1 2 $array5['one']='a';
3 if(!isset($array5[0]))
4 {
5 echo '

$array5[0] is empty of!

';
6 }
7 ?>

The result is:

$array5[0] is empty!

Explanation: $array5[0] represents the value of the element whose key is 0 in the array (it does not represent the first element of the array like C# and other languages), because the array only has keys that are characters For the element string 'one', there is no element with a key of 0, so $array5[0] is empty.

3>PHP supports two types of arrays: indexed array and associative array. The former uses numbers as keys, and the latter uses strings as keys. You can use a mix of numbers and strings as keys for elements when creating an array. The code is as follows:
Copy code The code is as follows:

1 2 $array9=array (1=>'a', 2=>'b', 'one'=>'c', 'two'=>'d', 'e', ​​'f', 'g');
3 echo '

The keys and values ​​of array $array9 are:

';
4 print_r($array9);
5 ?>

The result is:

The keys and values ​​of array $array9 are:

Array ( [1] => a [2] => b [one] => c [two] => d [3] => e [4] => f [5] => g )

4>Variables can also be used as keys of arrays, as shown below:
Copy code The code is as follows:

1 2 $key1='one';
3 $key2='two';
4 $key3='three';
5 $array10[$key1]='a';
6 $array10[$key2]='b';
7 $array10[$key3]='c';
8 echo '

The keys and values ​​of array $array10 are:

';
9 print_r($array10);
10 ?>

The result is:

The keys and values ​​of array $array10 are:

Array ( [one] => a [two] => b [three] => c )

2. How to access the elements of the array

1. General method

To get an element in the array elements, just use the array name plus brackets and a key. The calling method is as follows:

$arrayname[key];

2. Use the foreach result to traverse the array

If you want to access each array element, you can use a foreach loop:

Foreach ($array as $value)

{

//Do something with $value

}

The Foreach loop will iterate each element in the array $array and assign the value of each element to the $value variable. Here is an example:
Copy code The code is as follows:

1 2 $array11=array('a','b',' c','d','e');
3 echo '

The value of array $array11 is:';
4 foreach($array11 as $value)
5 {
6 echo $value.',';
7 }
8 echo '

';
9 ?>

The output result is:

The values ​​of array $array11 are: a,b,c,d,e,



Using foreach, you can also access the keys and values ​​of the array elements at the same time. You can use:

Foreach ($array as $key => $value)

{

//Do something with $key and $value

}

Where $key is the key of each element and $value is the value of the element. The following code demonstrates how to use the foreach structure to create a drop-down box:
Copy code The code is as follows:

1 2 $array12=array('one'=>1,'two'=>2,'three'= >3,'four'=>4,'five'=>5);
3 echo '


3. Use the list function to access the array

The List function assigns the values ​​in the array to some variables. The function syntax is as follows:

Void list(mixed varname, mixed varname2......)

Look at the following example:
Copy the code The code is as follows:

1 php
2 $array13=array('red','blue','green');
3 //Assign values ​​to all variables
4 list($flag1,$sky1,$grassland1)= $array13;
5 echo "$flag1 $sky1 $grassland1";
6 echo '
';
7 //Assign values ​​to some variables
8 list($flag2,,$ grassland2)=$array13;
9 echo "$flag2 $grassland2";
10 echo '
';
11 //Only assign value to the third variable
12 list(, ,$grassland3)=$array13;
13 echo "$grassland3";
14 echo '
';
15 ?>

The output result is:

red blue green
red green
green

Note: list() can only be used on numerically indexed arrays and the numerical index must start from 0.

Because the list function first assigns the element value with key 0 in the array to the first variable, and then assigns the element value with key 1 to the second variable, and so on, so in the list function The number and position of the variables must correspond to the numeric keys in the array to obtain the desired value, and the list function cannot access array elements with strings as keys. As shown below:
Copy code The code is as follows:

1 2 $array13=array( 1=>'red','blue','green');
3 list($flag1,$sky1,$grassland1)=$array13;
4 echo 'The value of $flag1 is:'. $flag1.'
';
5 echo 'The value of $sky1 is:'.$sky1.'
';
6 echo 'The value of $grassland1 is:'.$grassland1 .'
';
7 ?>

The output result is:

The value of $flag1 is:
The value of $sky1 is: red
The value of $grassland1 is: blue

Explanation: Because the value of $flag1 should be the element value with key 0 in the array, but the first element of this array has 1 as the key, and there is no key. 0 element, so the value of $flag1 is empty, which also causes the values ​​of $sky1 and $grassland1 to change later.

4. Use the each function to access the array

The each function returns the current key/value pair in the array and moves the array pointer forward one step. Note that it is a pair. Detailed description below. The function syntax:

array each ( array &$array )

Returns the key/value pair of the current pointer position in the array array and moves the array pointer forward. Each key-value pair is returned as a four-element array, with the key value being 0, 1, key and value. Elements 0 and key contain the key names of the array cells, and 1 and value contain the data. If the internal pointer is past the end of the array, each() returns FALSE. Why does each function have four tables below? In fact, the four subscripts obtained by each function are just for our convenience. We can use 0 and 1 as indexes, or key and value as indexes. Please look at the following code:
Copy code The code is as follows:

1 2 $arr=array ("I am the first value", "I am the second value", "I am the third value");
3 echo "When we use 0,1 as the index:
";
4 $a=each($arr);
5 echo "My key in the $arr array is: ".$a['0'];
6 echo "
";
7 echo "My value in the $arr array is: ".$a['1'];
8 echo "

";
9 echo "When we use key and value as index:

";
10 $b=each($arr) ;
11 echo "My key in the $arr array is: ".$b['key'];
12 echo "
";
13 echo "My key in $ The value in the arr array is: ".$b['value'];
14 ?>

is displayed as:

when we use 0,1 as the index When:
My key in the $arr array is: 0
My value in the $arr array is: I am the first value
When we use key, value as index:

My key in the $arr array is: 1
My value in the $arr array is: I am the second value

5. Use the each function combined with the list function. Traverse the array, as in the following example:
Copy code The code is as follows:

1 2 $array14= array('a' => 'apple', 'b' => 'banana', 'c' => 'cranberry');
3 while(list($key,$value) = each( $array14))
4 {
5 echo "$key => $valuen";
6 }
7 ?>

The output result is:

a => apple b => banana c => cranberry

6. Use for loop to access the array

as shown in the following example:
Copy code The code is as follows:

1 2 $array15=array('a','b','c','d','e','f');
3 for ($i=0;$i4 {
5 echo 'Array element:'.$array15[$i].'
';
6 }
7 ?>

The output result is:

Array element: a
Array element: b
Array element: c
Array element: d
Array element: e
Array element: f

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/323742.htmlTechArticle1. How to define an array: There are two main ways to create an array in PHP. Let us take a look below. How to create an array (1) Create an array by directly assigning a value to each element...
Statement
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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)