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 ""; echo "
"; echo "
"; print_r($vals); echo ""; ?>
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 ""; ?>
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 ""; ?>
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 ""; ?>
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); ?>
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 ""; ?>
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 ""; ?>
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 ""; ?>
<?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 ""; ?>
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 ""; ?>
不仅拆减,而且可以添加
<?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 ""; echo "
"; print_r($arr); echo ""; ?> array_merge(); "; print_r($arr); echo ""; ?>
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 ""; ?>
//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; ?>
Please indicate the source for reprinting: http://blog.csdn.net/junzaivip

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Chinese version
Chinese version, very easy to use

WebStorm Mac version
Useful JavaScript development tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver Mac version
Visual web development tools
