Table of Contents
PHP Lesson 7 Usage of Arrays 2
Home Backend Development PHP Tutorial PHP Lesson 7 Usage of Arrays 2_PHP Tutorial

PHP Lesson 7 Usage of Arrays 2_PHP Tutorial

Jul 13, 2016 am 10:19 AM
array

PHP Lesson 7 Usage of Arrays 2

Learning Outline:

1. Understand array functions

2. Randomly output verification code

1. Array function:



Array function:
//Function: Provides a lot of very useful code snippets written by the official to improve writing speed.

1. Array key value operation function
2. Count the elements and uniqueness of the array
3. Functions that use callback functions to process arrays
4. Array sorting function
5. Split, merge, decompose and combine functions
6. Arrays and data structures
7. Other useful array processing functions


Array key value operation function:
1.array_values();

Simulate getting the values ​​of key and value
<?php
								$arr=array("name"=>"user1","age"=>"30","sex"=>"man");


								foreach($arr as $key=>$val){
									$keys[]=$key;
									$vals[]=$val;
								}
									
										echo "<pre class="code">";
										print_r($keys);
										echo "
Copy after login
"; echo "
"; echo "
";
								print_r($vals);
								echo "
Copy after login
"; ?>



2.Usage of array_values
<?php
					$arr=array("name"=>"user1","age"=>"30","sex"=>"man");


					$keys=array_values($arr);


					echo "<pre class="code">";
					print_r($keys);
					echo "
Copy after login
"; ?>


array_values();//Get the values ​​in the array
array_keys();//Get the keys in the array
in_array();//Check whether a value is in the array
array_key_exists();//Check whether a key is in the array
array_flip(); //Key and value swap
array_reverse();Reverse the values ​​in the array


Count the elements and uniqueness of arrays
1.count();
2.array_count_values();//Count the number of occurrences of each value in the array.
3.array_unique();//Delete duplicates in the array


Functions that use callback functions to process arrays:
1.array_filter();
<?php
			$arr=array("user1"=>70,60,80,78,34,34,34,56,78,78);


			function older($var){
				return ($var>60);


			}


			$arr2=array_filter($arr,"older");
			
			echo "<pre class="code">";
			print_r($arr2);
			echo "
Copy after login
"; ?>

2.array_map();


Reference parameters:
Requirement: Array value increases by 1


function show(&$arr){
foreach($arr as $key=>$val){
$arr[$key]=$val+1;


}


}




Array sorting function
1.sort(); Ascending order, key is not retained
2.rsort(); Descending order, key is not retained
3.asort(); Ascending order, keep key
4.arsort(); Descending order, keep key
5.ksort(); Sort according to key in ascending order
6.krsort(); Sort by key in descending order
7.natsort(); natural number sorting in ascending order, such as the picture img2.jpg
8.natcasesort(); ignore case and sort in ascending order
9.multisort();Multiple array sorting




ksort();
<?php
		$arr=array("user1"=>10,"b"=>1,"c"=>3,"d"=>30);


		$arr2=array_flip($arr);


		ksort($arr2);


		echo "<pre class="code">";
		print_r($arr2);
		echo "
Copy after login
"; ?>



natsort();
<?php
		$array1 = $array2 = array("img12.png", "img10.png", "img2.png", "img1.png");


		sort($array1);
		echo "Standard sorting\n";
		print_r($array1);


		natsort($array2);
		echo "\nNatural order sorting\n";
		print_r($array2);
		?> 
Copy after login






Multi-array sorting:
<?php
		$arr=array("aaa","bbbbbbbbb","cc","ddddd");
		//需求:
		//1.按照标题长度排序
		//2.标题长度变成标题字符串的key


		//将数组中的value的长度取出,并作为一个新数组
		//strlen($val)取出字符串的长度
		foreach ($arr as  $val) {
			    $lens[]=strlen($val);
			}	


			
			array_multisort($lens,SORT_ASC,$arr);//对数组进行排序,根据第一个数组来排序第二个数组  SORT_ASC表示升序排序


			sort($lens);


			$arr2=array_combine($lens, $arr);//第一个数组作为第二个数组对应的key,返回一个新数组


			echo "<pre class="code">";
			print_r($arr2);
			echo "
Copy after login
"; ?>





Split, merge, decompose and combine functions
1.explode();
2.inplode();//join();
3.array_slice(); Array interception
4.array_splice(); Clipping of array
5.array-merge(); merge multiple arrays
6.array_combine(); merge arrays, two arrays, the former array as key, the latter array as value
7.array_intersect(); Find the intersection of two arrays
8.array_diff(); Find the difference between two arrays, based on the first parameter
9.array_pop(); pops a value from the end and returns the popup value
10.array_push(); Push a value from the last position and return the number of elements
11.array_shift(); delete a value from the position before washing
12.array_unshift(); Push a value from the front position


<?php


			$str="php,js,html,ces,div";
			$arr=explode(",",$str);


			echo "<pre class="code">";
			print_r($arr);
			echo "
Copy after login
"; ?>
Copy after login
2.inplode(); Combine arrays into strings
<?php


			$str="php,js,html,ces,div";
			$arr=explode(",",$str);


			$str2=implode("-",$arr);


			echo "<pre class="code">";
			print_r($str2);
			echo "
Copy after login
"; ?>





<?php


				$str="php,js,html,ces,div";
				$arr=explode(",",$str);


				$arr2=array_reverse($arr);//讲数组中的值进行倒序


				$str2=implode("-",$arr2);


				echo "<pre class="code">";
				print_r($str2);
				echo "
Copy after login
"; ?>




array_slice();
<?php
	
				//截取总是从后往前截取
			    $arr = array("aa","bb","cc","dd","ee","ff","gg");


			    $arr2 = array_slice($arr, 0,2);//表示从0的位置截取2个  aa bb
			    $arr3 = array_slice($arr, -3,2);//表示从后往前数到3的位置,开始截取2个//ee  ff


			    echo "<pre class="code">";
			     print_r($arr3);
			     echo "
Copy after login
"; ?>
不仅拆减,而且可以添加
Copy after login


<?php
		    $arr = array("aa","bb","cc","dd","ee","ff","gg");


		    $arr2 = array_splice($arr, 0, 3, array("hh","ii","jj","kk"));//直接取原数组的值,并将原数组进行改变,原数组为取走以后剩下的值


		    echo "<pre class="code">";
		    print_r($arr2);
		    echo "
Copy after login
"; echo "
";
		    print_r($arr);
		    echo "
Copy after login
Copy after login
"; ?> array_merge();
";
		    print_r($arr);
		    echo "
Copy after login
Copy after login
"; ?>





Other useful array processing functions:
1.array_rand();//Randomly pick a key
2.range();//Get an array of a certain range
3.shuffle();//The function of shuffling the array
4.array_sum();//Calculate the sum of all people in the array (calculate the total score)
If you calculate the key sum of an array, you can use array_flip() to swap the key sum values ​​of the array, and then you can calculate the key sum.








<?php
	
	
    $arr = array("aa","bb","cc","dd","ee","ff","gg");


    //将原数组顺序随机打乱
    shuffle($arr);


    //取出数组的前3个
    $arr2= array_slice($arr, 0 , 3);


    echo "<pre class="code">";
    print_r($arr2);
    echo "
Copy after login
"; ?>





//Randomly output four characters verification code implementation:
<?php
	
	//取出1-9 a-z A-Z的数组
    $a = range(1, 9);
    $b = range(a, z);
    $c = range(A, Z);


    //将3个数组合并
    $d = array_merge($a,$b,$c);


    //将合并后的数组打乱
    shuffle($d);


    //取合并后的前4位
    $e = array_slice($d, 0, 4);


    //将$e数组变为字符串
    $f = join("", $e);


    echo $f;






	?>	
Copy after login


Please indicate the source for reprinting: http://blog.csdn.net/junzaivip

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/871186.htmlTechArticlePHP Lesson 7 Usage of Arrays 2 Learning Outline: 1. Understand array functions 2. Randomly output verification codes 1. Array function: Array function: //Function: Provides a lot of very useful code snippets written by the official, providing...
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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
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)

How to remove duplicate elements from PHP array using foreach loop? How to remove duplicate elements from PHP array using foreach loop? Apr 27, 2024 am 11:33 AM

The method of using a foreach loop to remove duplicate elements from a PHP array is as follows: traverse the array, and if the element already exists and the current position is not the first occurrence, delete it. For example, if there are duplicate records in the database query results, you can use this method to remove them and obtain results without duplicate records.

PHP array key value flipping: Comparative performance analysis of different methods PHP array key value flipping: Comparative performance analysis of different methods May 03, 2024 pm 09:03 PM

The performance comparison of PHP array key value flipping methods shows that the array_flip() function performs better than the for loop in large arrays (more than 1 million elements) and takes less time. The for loop method of manually flipping key values ​​takes a relatively long time.

The Art of PHP Array Deep Copy: Using Different Methods to Achieve a Perfect Copy The Art of PHP Array Deep Copy: Using Different Methods to Achieve a Perfect Copy May 01, 2024 pm 12:30 PM

Methods for deep copying arrays in PHP include: JSON encoding and decoding using json_decode and json_encode. Use array_map and clone to make deep copies of keys and values. Use serialize and unserialize for serialization and deserialization.

PHP array multi-dimensional sorting practice: from simple to complex scenarios PHP array multi-dimensional sorting practice: from simple to complex scenarios Apr 29, 2024 pm 09:12 PM

Multidimensional array sorting can be divided into single column sorting and nested sorting. Single column sorting can use the array_multisort() function to sort by columns; nested sorting requires a recursive function to traverse the array and sort it. Practical cases include sorting by product name and compound sorting by sales volume and price.

Best Practices for Deep Copying PHP Arrays: Discover Efficient Methods Best Practices for Deep Copying PHP Arrays: Discover Efficient Methods Apr 30, 2024 pm 03:42 PM

The best practice for performing an array deep copy in PHP is to use json_decode(json_encode($arr)) to convert the array to a JSON string and then convert it back to an array. Use unserialize(serialize($arr)) to serialize the array to a string and then deserialize it to a new array. Use the RecursiveIteratorIterator to recursively traverse multidimensional arrays.

Application of PHP array grouping function in data sorting Application of PHP array grouping function in data sorting May 04, 2024 pm 01:03 PM

PHP's array_group_by function can group elements in an array based on keys or closure functions, returning an associative array where the key is the group name and the value is an array of elements belonging to the group.

PHP array merging and deduplication algorithm: parallel solution PHP array merging and deduplication algorithm: parallel solution Apr 18, 2024 pm 02:30 PM

The PHP array merging and deduplication algorithm provides a parallel solution, dividing the original array into small blocks for parallel processing, and the main process merges the results of the blocks to deduplicate. Algorithmic steps: Split the original array into equally allocated small blocks. Process each block for deduplication in parallel. Merge block results and deduplicate again.

The role of PHP array grouping function in finding duplicate elements The role of PHP array grouping function in finding duplicate elements May 05, 2024 am 09:21 AM

PHP's array_group() function can be used to group an array by a specified key to find duplicate elements. This function works through the following steps: Use key_callback to specify the grouping key. Optionally use value_callback to determine grouping values. Count grouped elements and identify duplicates. Therefore, the array_group() function is very useful for finding and processing duplicate elements.

See all articles