search
HomeBackend DevelopmentPHP Tutorial跟我学习php数组常用函数-上篇

对于php的初学者,也许会对它大量的函数不清楚该学习哪些。我在这列举了一些大家实际当中可能与使用到的,供您参考


1) array_map ( callable $callback , array $arr1 [, array $... ] )

callback(回调函数),接受一个函数函数作用:将arr1的参数顺序的传递给前面的回调函数

  • 回调函数有参时:
/*例1*/<?php function  cube ( $n ){    return( $n  *  $n  *  $n );} $a  = array( 1 ,  2 ,  3 ,  4 ,  5 ); $b  =  array_map ( "cube" ,  $a ); print_r ( $b );/** 输出 Array (     [0] => 1     [1] => 8     [2] => 27     [3] => 64     [4] => 125 )**/ ?>
  • 回调函数无参时:
<?php/*例2*//*将多个数组进行合并*/$a  = array( 1 ,  2 ,  3 ,  4 ,  5 ); $b  = array( "one" ,  "two" ,  "three" ,  "four" ,  "five" ); $c  = array( "uno" ,  "dos" ,  "tres" ,  "cuatro" ,  "cinco" ); $d  =  array_map ( null ,  $a ,  $b ,  $c ); print_r ( $d );/*输出Array(    [0] => Array        (            [0] => 1            [1] => one            [2] => uno        )    [1] => Array        (            [0] => 2            [1] => two            [2] => dos        )    [2] => Array        (            [0] => 3            [1] => three            [2] => tres        )    [3] => Array        (            [0] => 4            [1] => four            [2] => cuatro        )    [4] => Array        (            [0] => 5            [1] => five            [2] => cinco        ))*/ ?>

2) range ( mixed $start , mixed $limit [, number $step = 1 ] )

step表示间隔值,不写默认为1

/*例1,产生一组数字*/$nums = range(1, 5);print_r($nums);/*输出:Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 )*/$nums = range(1, 5, 2);print_r($nums);/*输出:Array ( [0] => 1 [1] => 3 [2] => 5 )*/
/*例2,产生一组字母数组*/$array = range('a','f');print_r($array);/*输出:Array ( [0] => a [1] => b [2] => c [3] => d [4] => e [5] => f )*/$array = array('a', 'f', 2);print_r($array);/*输出:print_r($array);/*输出:Array ( [0] => a [1] => c [2] => e )*/

3) array_merge ( array $array1 [, array $... ] )

array_merge() 将一个或多个数组的单元合并起来,一个数组中的值附加在前一个数组的后面。返回作为结果的数组。

如果输入的数组中有相同的字符串键名,则该键名后面的值将覆盖前一个值。然而,如果数组包含数字键名,后面的值将不会覆盖原来的值,而是附加到后面。

如果只给了一个数组并且该数组是数字索引的,则键名会以连续方式重新索引。

/*解释:如果只给了一个数组并且该数组是数字索引的,则键名会以连续方式重新索引。*/$array1 = array(1, 2, 3, 4, 5);$array2 = array(1, 2, 8, 9);$array3 = array_merge($array1, $array2);print_r($array3);/*输出:Array(    [0] => 1    [1] => 2    [2] => 3    [3] => 4    [4] => 5    [5] => 1    [6] => 2    [7] => 8    [8] => 9)*/

4) array_merge_recursive ( array $array1 [, array $... ] ) 递归地合并一个或多个数组

如果输入的数组中有相同的字符串键名,则这些值会被合并到一个数组中去,这将递归下去,因此如果一个值本身是一个数组,本函数将按照相应的条目把它合并为另一个数组。然而,如果数组具有相同的数组键名,后一个值将不会覆盖原来的值,而是附加到后面。

会根据键名相同一层一层的将值进行合并

/*例1*/$ar1 = array("color" => array("favorite" => "red"), 5);$ar2 = array(10, "color" => array("favorite" => array('a'=>"red"), "blue"));$result = array_merge_recursive($ar1, $ar2);print_r($result);/*输出:Array(    [color] => Array        (            [favorite] => Array                (                    [0] => red                    [a] => red     重点                )            [0] => blue        )    [0] => 5    [1] => 10)*/
/*例2*/$ar1 = array("color" => array("favorite" => "red"), 5);$ar2 = array(10, "color" => array("favorite" =>"red", "blue"));$result = array_merge_recursive($ar1, $ar2);print_r($result);/*输出:Array(    [color] => Array        (            [favorite] => Array                (                    [0] => red                    [1] => red  重点                )            [0] => blue        )    [0] => 5    [1] => 10)*/

5) array_pad ( array $input , int $pad_size , mixed $pad_value ) 给数组增加值到指定的长度,原数组不会改变

<?php$input = array(12, 10, 9);$result = array_pad($input, 5, 0);// result is array(12, 10, 9, 0, 0)$result = array_pad($input, -7, -1);// result is array(-1, -1, -1, -1, 12, 10, 9)$result = array_pad($input, 2, "noop");// not padded/*如果size<数组的长度,将不会有变化*/?>

6) array_pop ( array &$array ) 移出最后一个元素,原数组会改变

array_pop() 弹出并返回 array 数组的最后一个单元,并将数组 array 的长度减一。 如果 array 为空(或者不是数组)将返回 NULL 。 此外如果被调用不是一个数则会产生一个 Warning。

<?php$stack = array("orange", "banana", "apple", "raspberry");$fruit = array_pop($stack);print_r($stack);?>/*输出Array(    [0] => orange    [1] => banana    [2] => apple)*/

7) array_shift() 将数组开头的单元移出数组,原数组会改变, 使用此函数后会重置(reset())array 指针。

array_shift() 将 array 的第一个单元移出并作为结果返回,将 array 的长度减一并将所有其它单元向前移动一位。所有的数字键名将改为从零开始计数,文字键名将不变。 如果 array 为空(或者不是数组)将返回 NULL

8) int array_push ( array &$array , mixed $var [, mixed $... ] )

  • array_push() 将 array 当成一个栈,并将传入的变量压入 array 的末尾。array 的长度将根据入栈变量的数目增加
  • 返回处理后数组的元素个数

9) reset ( array &$array )将数组的内部指针指向第一个单元

  • reset() 将 array 的内部指针倒回到第一个单元并返回第一个数组单元的值。
  • 数组为空返回false

10) end ( array &$array )

参数array,该数组是通过引用(&)传递的,因为它会被这个函数修改。 这意味着你必须传入一个真正的变量,而不是函数返回的数组,因为只有真正的变量才能以引用传递。

  • end() 将 array 的内部指针移动到最后一个单元并返回其值。
  • 数组为空返回false
<?phpfuncation back(){    $arr = array(1, 2, 3);    return $arr;}/*上面引用传递的意思请注意看*/$num = end(back()); //错误!,因为该参数是引用传递$array = back();$num = end($array); //正确

对于引用传递,如果不将一个函数的返回值赋给一个变量的话,在内存中是不会真正的开辟以个单独的空间内存的。而引用传递的参数则必须需要一个有真实存在的内存的,因此,$array = back(),这样会开辟一片内存给$array变量

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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

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.

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

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.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool