


Detailed explanation of custom functions and array examples in php
1. Custom functions
Custom functions are functions defined by ourselves, customized in PHP The function format is as follows:
function funname(arg1, arg2, arg3......){ //TODO return values; }
<?php function fun($m, $n){ if($m==0 || $n==0){ return 0; }else{ $a=$m*$n; return $a; } } $p=2; $h=3; echo $p."*".$h."=".fun($p,$h); ?>
Output result: Let’s take another function with variable parameters
<?php /* function fun($m, $n){ if($m==0 || $n==0){ return 0; }else{ $a=$m*$n; return $a; } } $p=2; $h=3; echo $p."*".$h."=".fun($p,$h); */ function fun($m, $n=1, $x=2){ $a=$m*$n*$x; return $a; } $p=2; echo fun($p)."<br>"; // 2*1*2 = 4 echo fun($p, 3)."<br>"; // 2*3*2 = 12 echo fun($p, 3, 3)."<br>"; // 2*3*3 = 18 ?>
<?php /* function fun($m, $n){ if($m==0 || $n==0){ return 0; }else{ $a=$m*$n; return $a; } } $p=2; $h=3; echo $p."*".$h."=".fun($p,$h); */ /* function fun($m, $n=1, $x=2){ $a=$m*$n*$x; return $a; } $p=2; echo fun($p)."<br>"; // 2*1*2 = 4 echo fun($p, 3)."<br>"; // 2*3*2 = 12 echo fun($p, 3, 3)."<br>"; // 2*3*3 = 18 */ function fun(&$n){ $n=$n*$n; } $p=2; fun($p); echo $p; ?>
##2. Array definition assignment
1. Basic writing format of array
Simple form: array(value 1, Value 2, value 3, …….)
array(“aa”, 12, true, 2.2, “test”, 50); //Get data through array subscript
Complete Format: array(key 1=>value 1, key 2=>value 2, …)
array(“title”=>”aa”, “age”=>20); //The data can only be obtained through the key name
2. How to create an array
//第一种 $arr1=array(11, 22, 33, "44"); //第二种 $arr2=array('a'=>'11', 'b'=>'22'); //第三种 $arr3[0]='20'; $arr3[1]='30';
3. Array operation
1. Modify
$arr=array(11, 22, 33, 44); $arr[0]=55; //数组变为$arr=array(55, 22, 33, 44);
2. Delete
$arr=array(11, 22, 33, 44); unset($arr[0]); //数组变为$arr=array(22, 33, 44);
3. Use
$arr=array(11, 22, 33, 44); echo $arr[0]; $arr=array('a'=>11, 'b'=>22, 'c'=>33, 'd'=>44); echo $arr['b']];
4. Traverse
$arr=array('a'=>11, 'b'=>22, 'c'=>33, 'd'=>44); foreach($arr as $value){ //无键名 echo $value."<br>"; } foreach($arr as $id=>$value){ //输出键和值 echo $id..$value."<br>"; }
4. Two-dimensional array
$arr=array(array("1","11","111"), array("2","22","222")); echo $arr[1][2];
5. Array function
(1)
array_change_key_case(array, case)array: required, array.
case: Optional, CASE_LOWER (default value, lowercase letters return the keys of the array), CASE_UPPER (uppercase letters return the keys of the array)
Function: Convert all KEYs of the array to Uppercase or lowercase.
<?php $a=array("a"=>"Cat","b"=>"Dog","c"=>"Horse"); print_r(array_change_key_case($a,CASE_UPPER)); ?> 结果:Array ( [A] => Cat [B] => Dog [C] => Horse )
(2)array_chunk(array,size,preserve_key)
array: required.
size: Required, specifies how many elements each new array contains.
preserve_key: optional, true (preserve key name), false (new index)
Function: Divide an array into new array blocks.
<?php //array_chunk(array,size,preserve_key) $a1=array("a"=>"Cat","b"=>"Dog","c"=>"Horse","d"=>"Cow"); print_r(array_chunk($a1,2)); $a2=array("a"=>"Cat","b"=>"Dog","c"=>"Horse","d"=>"Cow"); print_r(array_chunk($a2,2,true)); ?>
Array ( [0] => Array ( [0] => Cat [1] => Dog ) [1] => Array ( [0] => Horse [1] => Cow ) )
Array ( [0] => Array ( [a] => Cat [b] => Dog ) [1] => Array ( [c] => Horse [ d] => Cow ) )
…….
There are many functions like this, you can check them when you use them, the list is as follows (php represents the first version)
Function | Description | PHP |
---|---|---|
array() | Create an array . | 3 |
array_change_key_case() | Returns an array whose keys are all uppercase or lowercase. | 4 |
array_chunk() | Split an array into new array chunks. | 4 |
array_combine() | Creates a new array by merging two arrays. | 5 |
array_count_values() | is used to count the number of occurrences of all values in the array. | 4 |
array_diff() | Returns the difference array of two arrays. | 4 |
array_diff_assoc() | Compare the key name and key value, and return the difference array of the two arrays. | 4 |
array_diff_key() | Compare the key names and return the difference array of the two arrays. | 5 |
array_diff_uassoc() | Calculate the difference set of the array by doing index checking through the callback function provided by the user. | 5 |
array_diff_ukey() | Use the callback function to compare the key names to calculate the difference set of the array. | 5 |
array_fill() | Fills the array with the given value. | 4 |
array_filter() | Use the callback function to filter the elements in the array. | 4 |
array_flip() | Exchange the keys and values in the array. | 4 |
array_intersect() | Calculate the intersection of arrays. | 4 |
array_intersect_assoc() | Compares the key name and key value, and returns the intersection array of the two arrays. | 4 |
array_intersect_key() | Calculate the intersection of arrays using key name comparison. | 5 |
array_intersect_uassoc() | Calculate the intersection of arrays with index checking, and use the callback function to compare the indexes. | 5 |
array_intersect_ukey() | Use the callback function to compare the key names to calculate the intersection of the arrays. | 5 |
array_key_exists() | Checks whether the given key name or index exists in the array. | 4 |
array_keys() | Returns all key names in the array. | 4 |
array_map() | Apply the callback function to the cells of the given array. | 4 |
array_merge() | Merge one or more arrays into one array. | 4 |
array_merge_recursive() | Recursively merge one or more arrays. | 4 |
array_multisort() | Sort multiple arrays or multidimensional arrays. | 4 |
array_pad() | Pads the array to the specified length with values. | 4 |
array_pop() | Pop the last unit of the array (pop off the stack). | 4 |
array_product() | Calculate the product of all values in an array. | 5 |
array_push() | Push one or more units (elements) to the end of the array (push). | 4 |
array_rand() | Randomly select one or more elements from the array and return it. | 4 |
array_reduce() | Use the callback function to iteratively reduce the array to a single value. | 4 |
array_reverse() | Reverse the order of elements in the original array, create a new array and return it. | 4 |
array_search() | Search for the given value in the array and return the corresponding key name if successful. | 4 |
array_shift() | Deletes the first element in the array and returns the value of the deleted element. | 4 |
array_slice() | Remove a segment of value from the array based on conditions and return it. | 4 |
array_splice() | Remove part of the array and replace it with other values. | 4 |
array_sum() | Calculate the sum of all values in an array. | 4 |
array_udiff() | Use the callback function to compare data to calculate the difference of the array. | 5 |
array_udiff_assoc() | Calculate the difference set of the array with index check, and use the callback function to compare the data. | 5 |
array_udiff_uassoc() | With index check, calculate the difference set of the array, and use the callback function to compare the data and index. | 5 |
array_uintersect() | Calculate the intersection of arrays and use callback functions to compare data. | 5 |
array_uintersect_assoc() | Calculate the intersection of arrays with index checking, and use callback functions to compare data. | 5 |
array_uintersect_uassoc() | Calculate the intersection of arrays with index checking, and use the callback function to compare the data and index. | 5 |
array_unique() | Remove duplicate values from the array. | 4 |
array_unshift() | Insert one or more elements at the beginning of the array. | 4 |
array_values() | Returns all the values in the array. | 4 |
array_walk() | Apply a user function to each member of the array. | 3 |
array_walk_recursive() | Applies a user function recursively to each member of an array. | 5 |
arsort() | Reverse sort the array and maintain the index relationship. | 3 |
asort() | Sort the array and maintain the index relationship. | 3 |
compact() | Create an array, including variable names and their values. | 4 |
count() | Calculate the number of elements in the array or the number of attributes in the object. | 3 |
current() | Returns the current element in the array. | 3 |
each() | Returns the current key/value pair in the array and moves the array pointer forward one step. | 3 |
end() | Point the internal pointer of the array to the last element. | 3 |
extract() | Import variables from the array into the current symbol table. | 3 |
in_array() | Checks whether the specified value exists in the array. | 4 |
key() | Get the key name from the associative array. | 3 |
krsort() | Sort the array in reverse order by key name. | 3 |
ksort() | Sort the array by key name. | 3 |
list() | Assign the values in the array to some variables. | 3 |
natcasesort() | Use the "natural sorting" algorithm to sort the array in a case-insensitive manner. | 4 |
natsort() | Sorts the array using the "natural sorting" algorithm. | 4 |
next() | Move the internal pointer in the array forward one position. | 3 |
pos() | An alias for current(). | 3 |
prev() | Rewind the internal pointer of the array by one bit. | 3 |
range() | Create an array containing elements in the specified range. | 3 |
reset() | Point the internal pointer of the array to the first element. | 3 |
rsort() | Sort the array in reverse order. | 3 |
shuffle() | Rearrange the elements in the array in random order. | 3 |
Alias for sizeof() | count(). | 3 |
sort() | Sort the array. | 3 |
uasort() | Use a user-defined comparison function to sort the values in an array and maintain index association. | 3 |
uksort() | Use a user-defined comparison function to sort the key names in the array. | 3 |
usort() | Use a user-defined comparison function to sort the values in the array. | 3 |
The above is the detailed content of Detailed explanation of custom functions and array examples in php. For more information, please follow other related articles on the PHP Chinese website!

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

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,

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

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.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

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.
