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
11 Best PHP URL Shortener Scripts (Free and Premium)11 Best PHP URL Shortener Scripts (Free and Premium)Mar 03, 2025 am 10:49 AM

Long URLs, often cluttered with keywords and tracking parameters, can deter visitors. A URL shortening script offers a solution, creating concise links ideal for social media and other platforms. These scripts are valuable for individual websites a

Introduction to the Instagram APIIntroduction to the Instagram APIMar 02, 2025 am 09:32 AM

Following its high-profile acquisition by Facebook in 2012, Instagram adopted two sets of APIs for third-party use. These are the Instagram Graph API and the Instagram Basic Display API.As a developer building an app that requires information from a

Working with Flash Session Data in LaravelWorking with Flash Session Data in LaravelMar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

Build a React App With a Laravel Back End: Part 2, ReactBuild a React App With a Laravel Back End: Part 2, ReactMar 04, 2025 am 09:33 AM

This is the second and final part of the series on building a React application with a Laravel back-end. In the first part of the series, we created a RESTful API using Laravel for a basic product-listing application. In this tutorial, we will be dev

Simplified HTTP Response Mocking in Laravel TestsSimplified HTTP Response Mocking in Laravel TestsMar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

cURL in PHP: How to Use the PHP cURL Extension in REST APIscURL in PHP: How to Use the PHP cURL Extension in REST APIsMar 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 CodeCanyon12 Best PHP Chat Scripts on CodeCanyonMar 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

Announcement of 2025 PHP Situation SurveyAnnouncement of 2025 PHP Situation SurveyMar 03, 2025 pm 04:20 PM

The 2025 PHP Landscape Survey investigates current PHP development trends. It explores framework usage, deployment methods, and challenges, aiming to provide insights for developers and businesses. The survey anticipates growth in modern PHP versio

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)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

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.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool