Home Backend Development PHP Tutorial Detailed explanation of php array function example tutorial

Detailed explanation of php array function example tutorial

Jul 25, 2016 am 08:51 AM

  1. $arr=array("name"=>"user1","age"=>"30","sex"=>"man") ;

  2. foreach($arr as $key=>$val){
  3. $keys[]=$key;
  4. $vals[]=$val;
  5. }
  6. echo "
    "; </li>
    <li>print_r($keys ); </li>
    <li>echo "
    ";
  7. echo "
    ";
  8. echo "
    "; </li>
    <li>print_r($vals); </li>
    <li>echo "
    ";
  9. ?>

Copy code

2.Usage of array_values

  1. $arr=array("name"=>"user1","age"=>"30","sex"=>"man");
  2. $keys =array_values($arr);
  3. echo "
    "; </li>
    <li>print_r($keys); </li>
    <li>echo "
    ";
  4. ?>
Copy code

array_values(); //Get the value 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();//Swapping keys and values 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();

  1. $arr=array("user1"=>70,60,80,78,34,34,34,56,78,78);
  2. function older($var) {
  3. return ($var>60);
  4. }
  5. $arr2=array_filter($arr,"older");
  6. echo "
    "; </li>
    <li>print_r($arr2); </li>
    <li>echo "
    ";
  7. ?>
Copy code

2.array_map(); Reference parameters: Requirement: Array value increases by 1

  1. function show(&$arr){
  2. foreach($arr as $key=>$val){
  3. $arr[$key]=$val+1;
  4. }
  5. }
Copy code

Sorting function of array 1.sort(); ascending order, key is not retained 2.rsort(); Descending order, key is not retained 3.asort(); ascending order, retain 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();

  1. $arr=array("user1"=>10,"b"=>1,"c"=>3,"d"=>30);
  2. $arr2=array_flip($arr);
  3. ksort($arr2);
  4. echo "
    "; </li>
    <li>print_r($arr2); </li>
    <li>echo "
    ";
  5. ?>
Copy Code

natsort();

  1. $array1 = $array2 = array("img12.png", "img10.png", "img2.png", "img1.png");
  2. sort($array1) ;
  3. echo "Standard sortingn";
  4. print_r($array1);
  5. natsort($array2);
  6. echo "nNatural order sortingn";
  7. print_r($array2);
  8. ?>
Copy code

Most Group sorting:

  1. $arr=array("aaa","bbbbbbbbb","cc","ddddd");
  2. //Requirements:
  3. //1. Sort by title length
  4. // 2. The title length becomes the key of the title string
  5. //Get the length of the value in the array and use it as a new array
  6. //strlen($val) to get the length of the string
  7. foreach ($arr as $val) {
  8. $lens[]=strlen($val);
  9. }
  10. array_multisort($lens,SORT_ASC,$arr);//Sort the array, sort the second array according to the first array SORT_ASC means ascending order
  11. sort($lens);
  12. $arr2=array_combine($lens, $arr);//The first array serves as the key corresponding to the second array, returning a new array
  13. echo "
    "; </li>
    <li>print_r( $arr2); </li>
    <li>echo "
    ";
  14. ?>
Copy code

Split, merge, decompose and combine functions 1.explode(); 2.inplode();//join(); 3.array_slice(); Array interception 4.array_splice(); Array cutting 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 pop-up 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 previous position 12.array_unshift(); Push a value from the front position

  1. $str="php,js,html,ces,div";
  2. $arr=explode(",",$str);
  3. echo "
    "; </li>
    <li> print_r($arr); </li>
    <li>echo "
    ";
  4. ?>
Copy code

2.inplode(); Combine arrays into strings

  1. $str="php,js,html,ces,div";
  2. $arr=explode(",",$str);
  3. $str2=implode ("-",$arr);
  4. echo "
    "; </li>
    <li>print_r($str2); </li>
    <li>echo "
    ";
  5. ?>

  6. < ;?php

  7. $str="php,js,html,ces,div";
  8. $arr=explode(",",$str);
  9. $arr2=array_reverse($arr);//Talk about the values ​​in the array Perform reverse order
  10. $str2=implode("-",$arr2);
  11. echo "
    "; </li>
    <li>print_r($str2); </li>
    <li>echo "
    ";
  12. ?>
Copy code

array_slice();

  1. //Interception is always taken from back to front
  2. $arr = array("aa","bb","cc","dd","ee","ff" ,"gg");
  3. $arr2 = array_slice($arr, 0,2);//Indicates that 2 aa bbs are intercepted from the 0 position
  4. $arr3 = array_slice($arr, -3,2);//Indicates Count from the back to the position of 3, start to intercept 2 //ee ff
  5. echo "
    "; </li>
    <li>print_r($arr3); </li>
    <li>echo "
    ";
  6. ?>
Copy the code

Not only can it be removed and subtracted, but it can also be added

  1. $arr = array("aa","bb","cc","dd","ee","ff","gg");
  2. $arr2 = array_splice ($arr, 0, 3, array("hh","ii","jj","kk"));//Directly take the value of the original array and change the original array. The original array will be the value after removal The remaining values ​​
  3. echo "
    "; </li>
    <li>print_r($arr2); </li>
    <li>echo "
    ";
  4. echo "
    "; </li>
    <li>print_r($arr); </li>
    <li>echo "&lt ;/pre>"; </li>
    <li>?></li>
    </ol></div>
    <em onclick="copycode($('code_bSa'));">Copy code</em>
    </div>
    <p>array_merge();
     </p>
    <div class="blockcode">
    <div id="code_kMp"><ol>
    <li>
    <li><?php </li>
    <li>$a = array("aa","bb","cc"); </li>
    <li>$b = array("dd","ee","ff","gg" ); </li>
    <li>$arr = array_merge($a, $b); </li>
    <li>echo "<pre class="brush:php;toolbar:false">"; </li>
    <li>print_r($arr); </li>
    <li>echo "
    ";
  5. ?>
Copy Code

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 disrupting 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 calculate the key sum.

  1. $arr = array("aa","bb","cc","dd","ee","ff","gg");
  2. //Randomly shuffle the order of the original array
  3. shuffle($arr);
  4. //Get the first 3 items of the array
  5. $arr2= array_slice($arr, 0, 3);
  6. echo "
    "; </li>
    <li> print_r($arr2); </li>
    <li>echo "
    ";
  7. ?>
  8. //Randomly output four-character verification code implementation:

  9. //Take out 1-9 a-z A-Z array

  10. $a = range(1, 9);
  11. $b = range(a, z);
  12. $c = range(A, Z);
  13. //Combine 3 arrays
  14. $ d = array_merge($a,$b,$c);
  15. //Shuffle the merged array
  16. shuffle($d);
  17. //Get the first 4 digits after the merge
  18. $e = array_slice($d, 0, 4);
  19. //Convert the $e array into a string
  20. $f = join("", $e);
  21. echo $f;
  22. ?>

Copy code


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 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 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)

cURL in PHP: How to Use the PHP cURL Extension in REST APIs cURL in PHP: How to Use the PHP cURL Extension in REST APIs Mar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

12 Best PHP Chat Scripts on CodeCanyon 12 Best PHP Chat Scripts on CodeCanyon Mar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Explain the concept of late static binding in PHP. Explain the concept of late static binding in PHP. Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Framework Security Features: Protecting against vulnerabilities. Framework Security Features: Protecting against vulnerabilities. Mar 28, 2025 pm 05:11 PM

Article discusses essential security features in frameworks to protect against vulnerabilities, including input validation, authentication, and regular updates.

Customizing/Extending Frameworks: How to add custom functionality. Customizing/Extending Frameworks: How to add custom functionality. Mar 28, 2025 pm 05:12 PM

The article discusses adding custom functionality to frameworks, focusing on understanding architecture, identifying extension points, and best practices for integration and debugging.

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

See all articles