search
HomeBackend DevelopmentPHP TutorialPHP Mobile Internet Development Notes (4) - Custom Functions and Arrays_PHP Tutorial

1. Custom function

Custom functions are functions that we define ourselves. The format of custom functions in PHP is as follows:

function funname(arg1, arg2, arg3...){

//TODO

return values;

}

  1. 	<?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:

The following is 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  
?>  

Let’s take a look at custom function reference passing

	<?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 and assignment

1. Basic writing format of array

Simple form: array(value1, value2, value3, ..........)

array("aa", 12, true, 2.2, "test", 50); //Get data through array subscript

Full form: array(key1=>value1, key2=>value2, ...)

array("title"=>"aa", "age"=>20); //Data can only be obtained by key name

2. How to create an array

	//第一种  
$arr1=array(11, 22, 33, "44");  
//第二种  
$arr2=array(&#39;a&#39;=>&#39;11&#39;, &#39;b&#39;=>&#39;22&#39;);  
//第三种  
$arr3[0]=&#39;20&#39;;  
$arr3[1]=&#39;30&#39;;  

3. Array operations

1. Modification

$arr=array(11, 22, 33, 44);

$arr[0]=55; //The array becomes $arr=array(55, 22, 33, 44);

2. Delete

$arr=array(11, 22, 33, 44);

unset($arr[0]); //The array becomes $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){ //No key name

echo $value."
";

}

foreach($arr as $id=>$value){ //Output key and value

echo $id."__".$value."
";

}

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 key of the array), CASE_UPPER (uppercase letters return the key of the array)

Function: Convert all KEYs in the array to uppercase or lowercase.

  1. 	<?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 using 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 blocks. 4
array_combine() Create a new array by merging two arrays. 5
array_count_values() 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 key names and return the difference array of the two arrays. 5
array_diff_uassoc() Calculate the difference set of arrays 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 and calculate the difference set of the array. 5
array_fill() Fills the array with the given values. 4
array_filter() Use callback function to filter the elements in the array. 4
array_flip() Swap the keys and values ​​in the array. 4
array_intersect() Calculate the intersection of arrays. 4
array_intersect_assoc() Compare the key name and key value and return 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 callback functions to compare the indices. 5
array_intersect_ukey() Use callback function to compare key names to calculate the intersection of arrays. 5
array_key_exists() Checks whether the given key 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() Combine 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() Pall the array to the specified length with values. 4
array_pop() Pop the last element 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 cells (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 a 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() Retrieve a value from the array based on the condition 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 callback function to compare data to calculate the difference of arrays. 5
array_udiff_assoc() Calculate the difference set of arrays with index checking, and use callback functions to compare 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 callback functions to compare data and indexes. 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 values ​​in the array. 4
array_walk() Apply a user function to each member of the array. 3
array_walk_recursive() Apply the user function recursively to each member of the array. 5
arsort() Reverse sort the array and maintain index relationship. 3
asort() Sort the array and maintain index relationship. 3
compact() Create an array including variable names and their values. 4
count() Count the number of elements in an array or the number of attributes in an 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() Sort the array in a case-insensitive manner using the "natural sorting" algorithm. 4
natsort() Sort 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
sizeof() An alias for count(). 3
sort() Sort the array. 3
uasort() Use user-defined comparison functions to sort values ​​in an array and maintain index association. 3
uksort() Use user-defined comparison function to sort the keys in the array. 3
usort() Sort the values ​​in an array using a user-defined comparison function. 3


www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/746360.htmlTechArticle1. Custom functions Custom functions are functions that we define ourselves. The format of custom functions in PHP is as follows: function funname(arg1, arg2, arg3...){ //TODO return values; } ?...
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
How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

How does PHP handle object cloning (clone keyword) and the __clone magic method?How does PHP handle object cloning (clone keyword) and the __clone magic method?Apr 17, 2025 am 12:24 AM

In PHP, use the clone keyword to create a copy of the object and customize the cloning behavior through the \_\_clone magic method. 1. Use the clone keyword to make a shallow copy, cloning the object's properties but not the object's properties. 2. The \_\_clone method can deeply copy nested objects to avoid shallow copying problems. 3. Pay attention to avoid circular references and performance problems in cloning, and optimize cloning operations to improve efficiency.

PHP vs. Python: Use Cases and ApplicationsPHP vs. Python: Use Cases and ApplicationsApr 17, 2025 am 12:23 AM

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

Describe different HTTP caching headers (e.g., Cache-Control, ETag, Last-Modified).Describe different HTTP caching headers (e.g., Cache-Control, ETag, Last-Modified).Apr 17, 2025 am 12:22 AM

Key players in HTTP cache headers include Cache-Control, ETag, and Last-Modified. 1.Cache-Control is used to control caching policies. Example: Cache-Control:max-age=3600,public. 2. ETag verifies resource changes through unique identifiers, example: ETag: "686897696a7c876b7e". 3.Last-Modified indicates the resource's last modification time, example: Last-Modified:Wed,21Oct201507:28:00GMT.

Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1?Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1?Apr 17, 2025 am 12:06 AM

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values ​​to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP: An Introduction to the Server-Side Scripting LanguagePHP: An Introduction to the Server-Side Scripting LanguageApr 16, 2025 am 12:18 AM

PHP is a server-side scripting language used for dynamic web development and server-side applications. 1.PHP is an interpreted language that does not require compilation and is suitable for rapid development. 2. PHP code is embedded in HTML, making it easy to develop web pages. 3. PHP processes server-side logic, generates HTML output, and supports user interaction and data processing. 4. PHP can interact with the database, process form submission, and execute server-side tasks.

PHP and the Web: Exploring its Long-Term ImpactPHP and the Web: Exploring its Long-Term ImpactApr 16, 2025 am 12:17 AM

PHP has shaped the network over the past few decades and will continue to play an important role in web development. 1) PHP originated in 1994 and has become the first choice for developers due to its ease of use and seamless integration with MySQL. 2) Its core functions include generating dynamic content and integrating with the database, allowing the website to be updated in real time and displayed in personalized manner. 3) The wide application and ecosystem of PHP have driven its long-term impact, but it also faces version updates and security challenges. 4) Performance improvements in recent years, such as the release of PHP7, enable it to compete with modern languages. 5) In the future, PHP needs to deal with new challenges such as containerization and microservices, but its flexibility and active community make it adaptable.

Why Use PHP? Advantages and Benefits ExplainedWhy Use PHP? Advantages and Benefits ExplainedApr 16, 2025 am 12:16 AM

The core benefits of PHP include ease of learning, strong web development support, rich libraries and frameworks, high performance and scalability, cross-platform compatibility, and cost-effectiveness. 1) Easy to learn and use, suitable for beginners; 2) Good integration with web servers and supports multiple databases; 3) Have powerful frameworks such as Laravel; 4) High performance can be achieved through optimization; 5) Support multiple operating systems; 6) Open source to reduce development costs.

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)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

mPDF

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),

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.

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.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment