search
HomeBackend DevelopmentPHP TutorialDetailed explanation of php array function example tutorial

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

  2. foreach($arr as $key=>$val){
  3. $keys[]=$key;
  4. $vals[]=$val;
  5. }
  6. echo "
    "; 
  7. print_r($keys );
  8. echo "";
  9. echo "
    ";
  10. echo "
    "; 
  11. print_r($vals);
  12. echo ""; p>
  13. ?>

Copy code

2.Usage of array_values

  1. $arr=array("name"=>"user1","age"=>"30","sex"=>"man");
  2. $keys =array_values($arr);
  3. echo "
    "; 
  4. print_r($keys);
  5. echo "";
  6. ?>
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 "
    "; 
  7. print_r($arr2);
  8. echo " ";
  9. ?>
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 "
    "; 
  5. print_r($arr2);
  6. echo "";
  7. ?>
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 "
    "; 
  14. print_r( $arr2);
  15. echo "";
  16. ?>
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 "
    "; 
  4. print_r($arr);
  5. echo "";
  6. ?>
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 "
    "; 
  5. print_r($str2);
  6. echo "";
  7. ?>
  8. < ;?php

  9. $str="php,js,html,ces,div";
  10. $arr=explode(",",$str);
  11. $arr2=array_reverse($arr);//Talk about the values ​​in the array Perform reverse order
  12. $str2=implode("-",$arr2);
  13. echo "
    "; 
  14. print_r($str2);
  15. echo "";
  16. ?>
  17. p>
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 "
    "; 
  6. print_r($arr3);
  7. echo "";
  8. ?>
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 "
    "; 
  4. print_r($arr2);
  5. echo "";
  6. echo "
    "; 
  7. print_r($arr);
  8. echo "< ;/pre>";
  9. ?>
Copy code

array_merge();

  1. $a = array("aa","bb","cc");
  2. $b = array("dd","ee","ff","gg" );
  3. $arr = array_merge($a, $b);
  4. echo "
    "; 
  5. print_r($arr);
  6. echo "";
  7. ?>
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 "
    "; 
  7. print_r($arr2);
  8. echo "";
  9. ?>
  10. //Randomly output four-character verification code implementation:
  11. //Take out 1-9 a-z A-Z array

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


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
PHP's Purpose: Building Dynamic WebsitesPHP's Purpose: Building Dynamic WebsitesApr 15, 2025 am 12:18 AM

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

PHP: Handling Databases and Server-Side LogicPHP: Handling Databases and Server-Side LogicApr 15, 2025 am 12:15 AM

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

How do you prevent SQL Injection in PHP? (Prepared statements, PDO)How do you prevent SQL Injection in PHP? (Prepared statements, PDO)Apr 15, 2025 am 12:15 AM

Using preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.

PHP and Python: Code Examples and ComparisonPHP and Python: Code Examples and ComparisonApr 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 in Action: Real-World Examples and ApplicationsPHP in Action: Real-World Examples and ApplicationsApr 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: Creating Interactive Web Content with EasePHP: Creating Interactive Web Content with EaseApr 14, 2025 am 12:15 AM

PHP makes it easy to create interactive web content. 1) Dynamically generate content by embedding HTML and display it in real time based on user input or database data. 2) Process form submission and generate dynamic output to ensure that htmlspecialchars is used to prevent XSS. 3) Use MySQL to create a user registration system, and use password_hash and preprocessing statements to enhance security. Mastering these techniques will improve the efficiency of web development.

PHP and Python: Comparing Two Popular Programming LanguagesPHP and Python: Comparing Two Popular Programming LanguagesApr 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.

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.

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

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)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

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.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools