Home Backend Development PHP Tutorial PHP study notes: Definition and traversal of arrays_PHP tutorial

PHP study notes: Definition and traversal of arrays_PHP tutorial

Jul 13, 2016 am 10:50 AM
php Can study definition object data array yes of notes type Traverse

Array in php is a special data type, which can be said to be an object or a memory. It can store the content of other data types in php, such as an array can contain characters, numbers, objects, etc. Wait, let me first learn the definition and traversal search of php arrays.

① The first method of creating an array

$arr[0]=123;
$arr[1]=90;
….

Concept:
[0] -> We call this subscript, or keyword
$arr[0] -> This is called an element of the array.
$arr[0]=123; 123 means the value corresponding to the $arr[0] element
$arr –》This is the name of the array.
☞In PHP arrays, the value stored in an element can be of any data type

② The second way to create an array

Basic Grammar
$array name=array(value 1, value 2,....);
Example:
$arr=array(1,90,"helllo",89.5);


③ The third way to create an array (By default, the subscripts of our elements are numbered starting from 0, but in fact, you can also specify it yourself)


Basic syntax $arr[‘logo’]=”Beijing”;
$arr[’hsp’]=123;
....
or
$arr=array("logo"=>"Beijing","hsp"=>123,4=>678);

Array traversal method:


Note: If you use for while do..while, you must make sure that the subscripts of the array are arranged sequentially starting from 0
To find out how many elements there are in the array, you can use the system function count

//

The code is as follows Copy code
 代码如下 复制代码

for循环遍历方法
for($i=0;$i echo '
'.$arr[$i];
}

//while循环遍历方法
$i=0;//循环控制变量
while($i echo "
".$colors[$i];
$i++;
}

//do..while
$i=0;//循环控制变量
do{
echo "
".$colors[$i];
$i++;
}while($i

//foreach 遍历方法
这个foreach适用范围更广
foreach($arr as $key=>$val){
echo $key."=".$val."
";
}

For loop traversal method

for($i=0;$i echo '
'.$arr[$i]; }

//while loop traversal method
$i=0;//Loop control variable
while($i echo "
".$colors[$i];
$i++;
}

//do..while
$i=0;//Loop control variable
do{
echo "
".$colors[$i];

$i++;

}while($i //foreach traversal method

This foreach has a wider scope of application

foreach($arr as $key=>$val){

echo $key."=".$val."
";
 代码如下 复制代码

$arr_a = array(0 => "a", 1 => "b", 2 => "c");
$key = array_search("a", $arr_a);
if( $key !== FALSE ){
    echo "键名为:$key";
} else {
    echo '无匹配结果';
}
?>

}
php array related functions ① count function The basic usage is count($array name); can count how many elements there are in the array. ② is_array ③ print_r and var_dump ④ explode split the string Case: $str="Zhejiang&Taizhou&Hangzhou"; //In actual development, when it comes to string splitting, you can consider $arr=explode("&",$str); print_r($arr); Array search Example:
The code is as follows Copy code
$arr_a = array(0 => "a", 1 => "b", 2 => "c"); $key = array_search("a", $arr_a); if( $key !== FALSE ){ echo "Key name: $key"; } else { echo 'No matching results'; } ?>

The example output results are as follows:

Key name: 0

array_key_exists() function


The function array_key_exists() returns true if a specified key is found in an array, false otherwise. Its form is as follows:

boolean array_key_exists(mixed key,array array);

The following example will search for apple in the array key, and if found, will output the color of the fruit:

The code is as follows Copy code
 代码如下 复制代码

$fruit["apple"] = "red";
$fruit["banana"] = "yellow";
$fruit["pear"] = "green";
if(array_key_exists("apple", $fruit)){
 printf("apple's color is %s",$fruit["apple"]);
}

$fruit["apple"] = "red";

$fruit["banana"] = "yellow";

$fruit["pear"] = "green";

if(array_key_exists("apple", $fruit)){

printf("apple's color is %s",$fruit["apple"]);

}


The result of executing this code: apple's color is red



Merge arrays

The array_merge() function merges arrays together and returns a combined array. The resulting array starts with the first input array parameter, and is added sequentially in the order in which subsequent array parameters appear. Its form is:

Php code

array array_merge (array array1 array2…,arrayN)

 代码如下 复制代码

$fruits = array("apple","banana","pear");
$numbered = array("1","2","3");
$cards = array_merge($fruits, $numbered);
print_r($cards);

// output
// Array ( [0] => apple [1] => banana [2] => pear [3] => 1 [4] => 2 [5] => 3 )
?>

This function combines the cells of one or more arrays, and the values ​​in one array are appended to the previous array. Returns the resulting array.

If there is the same string key name in the input array, the value after the key name will overwrite the previous value. However, if the array contains numeric keys, the subsequent values ​​will not overwrite the original values, but will be appended to them.

If only an array is given and the array is numerically indexed, the key names are re-indexed consecutively.

The code is as follows Copy code
$fruits = array("apple","banana","pear");

$numbered = array("1","2","3");

$cards = array_merge($fruits, $numbered);

print_r($cards);

//output
代码如下 复制代码

$fruit1 = array("apple" => "red", "banana" => "yellow");
$fruit2 = array("pear" => "yellow", "apple" => "green");
$result = array_merge_recursive($fruit1, $fruit2);
print_r($result);

// output
// Array ( [apple] => Array ( [0] => red [1] => green ) [banana] => yellow [pear] => yellow )
?>   

// Array ( [0] => apple [1] => banana [2] => pear [3] => 1 [4] => 2 [5] => 3 ) ?> 2. Append array The array_merge_recursive() function is the same as array_merge(). It can merge two or more arrays together to form a combined array. The difference between the two is that the function will handle it differently when a key in an input array already exists in the result array. array_merge() will overwrite the previously existing key/value pairs and replace them with the key/value pairs in the current input array, while array_merge_recursive() will merge the two values ​​together to form a new array with the original keys. as an array name. There is also a form of array merging, which is to recursively append arrays. Its form is: Php code array array_merge_recursive(array array1,array array2[…,array arrayN]) The program example is as follows:
The code is as follows Copy code
$fruit1 = array("apple" => "red", "banana" => "yellow"); $fruit2 = array("pear" => "yellow", "apple" => "green"); $result = array_merge_recursive($fruit1, $fruit2); print_r($result); //output // Array ( [apple] => Array ( [0] => red [1] => green ) [banana] => yellow [pear] => yellow ) ?>

Now the key apple points to an array consisting of two indexed arrays of color values.

3. Connect arrays
The array_combine() function will get a new array, which consists of a set of submitted keys and corresponding values. Its form is:

array array_combine(array keys,array values)

Note that the two input arrays must be of the same size and cannot be empty. An example is as follows

The code is as follows Copy code
 代码如下 复制代码


$name = array("apple", "banana", "orange");
$color = array("red", "yellow", "orange");
$fruit = array_combine($name, $color);
print_r($fruit);

// output
// Array ( [apple] => red [banana] => yellow [orange] => orange )
?>

 

$name = array("apple", "banana", "orange"); $color = array("red", "yellow", "orange");

$fruit = array_combine($name, $color);

print_r($fruit);

//output

// Array ( [apple] => red [banana] => yellow [orange] => orange )

?>

 代码如下 复制代码

$fruits = array("Apple", "Banana", "Orange", "Pear", "Grape", "Lemon", "Watermelon");
$subset = array_slice($fruits, 3);
print_r($subset);

// output
// Array ( [0] => Pear [1] => Grape [2] => Lemon [3] => Watermelon )
?>

4. Split array array_slice()
The array_slice() function will return a part of the array, starting from the key offset and ending at offset+length. Its form:

Php code

array array_slice (array array, int offset[,int length])

When offset is a positive value, splitting will start from the offset position from the beginning of the array; if offset is a negative value, splitting will start from the offset position from the end of the array. If the optional length parameter is omitted, the split will start at offset and go to the last element of the array. If length is given and is positive, it ends at offset+length from the beginning of the array. Conversely, if length is given and is negative, it ends at count(input_array)-|length| from the beginning of the array. Consider an example:

The code is as follows Copy code
$fruits = array("Apple", "Banana", "Orange", "Pear", "Grape", "Lemon", "Watermelon"); $subset = array_slice($fruits, 3);

print_r($subset);

//output
代码如下 复制代码

$arr = array(
‘d’ => array(‘id’ => 5, ‘name’ => 1, ‘age’ => 7),
‘b’ => array(‘id’ => 2,’name’ => 3,’age’ => 4),
‘a’ => array(‘id’ => 8,’name’ => 10,’age’ => 5),
‘c’ => array(‘id’ => 1,’name’ => 2,’age’ => 2)
);

// Array ( [0] => Pear [1] => Grape [2] => Lemon [3] => Watermelon ) ?> Array sorting (the following method is used for one-dimensional arrays) •The sort() function is used to sort array cells from low to high. •rsort() function is used to sort array cells from high to low. •asort() function is used to sort array cells from low to high and maintain index relationship. •The arsort() function is used to sort the array cells from high to low and maintain the index relationship. •The ksort() function is used to sort array cells from low to high by key name. •The krsort() function is used to sort array cells from high to low by key name. Multidimensional array sorting For example, there is a mostly array:
The code is as follows Copy code
$arr = array( ‘d’ => array(‘id’ => 5, ‘name’ => 1, ‘age’ => 7), ‘b’ => array(‘id’ => 2, ‘name’ => 3, ‘age’ => 4), ‘a’ => array(‘id’ => 8, ‘name’ => 10, ‘age’ => 5), ‘c’ => array(‘id’ => 1, ‘name’ => 2, ‘age’ => 2) );

Need to sort the age items in the two-dimensional array.

You need to use PHP’s built-in function array_multisort(), you can read the manual.

Custom function:

function multi_array_sort($multi_array,$sort_key,$sort=SORT_ASC){
if(is_array($multi_array)){
foreach ($multi_array as $row_array){
if(is_array($row_array)){
$key_array[] = $row_array[$sort_key];
}else{
return false;
}
}
}else{
return false;
}
array_multisort($key_array,$sort,$multi_array);
return $multi_array;
}
The code is as follows
 代码如下 复制代码

function multi_array_sort($multi_array,$sort_key,$sort=SORT_ASC){
if(is_array($multi_array)){
foreach ($multi_array as $row_array){
if(is_array($row_array)){
$key_array[] = $row_array[$sort_key];
}else{
return false;
}
}
}else{
return false;
}
array_multisort($key_array,$sort,$multi_array);
return $multi_array;
}

//处理

echo “

”;
print_r(multi_array_sort($arr,’age’));exit;

//输出

Array
(
[c] => Array
(
[id] => 1
[name] => 2
[age] => 2
)

[b] => Array
(
[id] => 2
[name] => 3
[age] => 4
)

[a] => Array
(
[id] => 8
[name] => 10
[age] => 5
)

[d] => Array
(
[id] => 5
[name] => 1
[age] => 7
)

)

Copy code

//Processing

echo “

”;
print_r(multi_array_sort($arr,’age’));exit;

Array
(
[c] => Array
(
[id] => 1
[name] => 2
[age] => 2
)
[b] => Array
(
[id] => 2
[name] => 3
[age] => 4
)
[a] => Array
(
[id] => 8
[name] => 10
[age] => 5
)
[d] => Array
(
[id] => 5
[name] => 1
[age] => 7
)
)
written by Daewoo
http://www.bkjia.com/PHPjc/632628.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/632628.htmlTechArticleArray in php is a special data type. It can be said to be an object or a memory. It can Store content of other data types in php, such as an array that can contain character types...
Statement of this Website
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

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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1253
24
PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 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.

See all articles