PHP array操作10个小技巧分享
其实任何一门计算机语言中对array(数组)的操作都是一门学问,PHP也不例外。下面笔者想向各位介绍关于PHP中array操作的10个小技巧及相关的函数。
1、向array中添加元素
php是一个弱类型语言。因此不必象c语言那样为php array声明长度。向其中添加元素的过程也是声明和初始化的过程。
代码如下:
$capitals = array(
'Alabama' => 'Montgomery',
'Alaska' => 'Juneau',
'Arizona' => 'Phoenix'
);
继续添加元素也很简单
代码如下:
$capitals['Arkansas'] = 'Little Rock';
如果不是关联数组而只是数字索引的数组可以使用array_push()和array_unshift()函数增加元素
2、从array中删除元素
从数组中移除元素可以使用unset() 函数
代码如下:
unset($capitals['California']);
也可以使用array_pop()或array_shift()函数从数组头或尾部顺序移除元素
3、array键值互换
如果希望新建数组的键是老数组的值而值是老数组的键,简而言之就是键值对调,则可以使用array_flip()函数完成操作
代码如下:
$capitals = array(
'Alabama' => 'Montgomery',
'Alaska' => 'Juneau',
'Arizona' => 'Phoenix'
);
$states = array_flip($capitals);
// $states = array(
// 'Montgomery' => string 'Alabama',
// 'Juneau' => string 'Alaska',
// 'Phoenix' => string 'Arizona'
// );
4、合并数组
如果希望将两个或多个数组合并成一个新的数组,array_merge()函数可以帮上这个忙^_^
代码如下:
$stateCapitals = array(
'Alabama' => 'Montgomery',
'Alaska' => 'Juneau',
'Arizona' => 'Phoenix'
);
$countryCapitals = array (
'Australia' => 'Canberra',
'Austria' => 'Vienna',
'Algeria' => 'Algiers'
);
$capitals = array_merge($stateCapitals, $countryCapitals);
5、修改array中的值
譬如希望将数组的中值全部改为小写后大写首字母,使用回调函数递归地对每个数组成员调用是个不错的方法,php中这个函数是php_map()
代码如下:
function capitalize($element)
{
$element = strtolower($element);
return ucwords($element);
}
$capitals = array(
'Alabama' => 'montGoMEry',
'Alaska' => 'Juneau',
'Arizona' => 'phoeniX'
);
$capitals = array_map("capitalize", $capitals);
6、根据array的键为数组排序
代码如下:
$capitals = array(
'Arizona' => 'Phoenix',
'Alaska' => 'Juneau',
'Alabama' => 'Montgomery'
);
ksort($capitals);
7、随机化array元素的顺序
shuffle() 和上面的ksort()函数恰恰相反,可以打乱数组现有的秩序,以达到随机化的目的。
代码如下:
$capitals = array(
'Arizona' => 'Phoenix',
'Alaska' => 'Juneau',
'Alabama' => 'Montgomery'
);
shuffle($capitals);
8、查找键或值是否存在
查找是否存在值使用in_array()函数
代码如下:
$capitals = array(
'Arizona' => 'Phoenix',
'Alaska' => 'Juneau',
'Alabama' => 'Montgomery'
);
if (in_array("Juneau", $capitals))
{
echo "Exists!";
} else {
echo "Does not exist!";
}
查找是否存在键使用array_key_exists()函数
代码如下:
$capitals = array(
'Arizona' => 'Phoenix',
'Alaska' => 'Juneau',
'Alabama' => 'Montgomery'
);
if (array_key_exists("Alaska", $capitals))
{
echo "Key exists!";
} else {
echo "Key does not exist!";
}
9、数组查找
这个是老生常谈了,基本上都用的到array_search()函数
代码如下:
$capitals = array(
'Arizona' => 'Phoenix',
'Alaska' => 'Juneau',
'Alabama' => 'Montgomery'
);
$state = array_search('Juneau', $capitals);
// $state = 'Alaska'
10、使用php标准函数库
一口气介绍这个多操作array的函数,如果您还觉得不过瘾,可以继续查看Standard PHP Library 中的内容^_^
代码如下:
$capitals = array(
'Arizona' => 'Phoenix',
'Alaska' => 'Juneau',
'Alabama' => 'Montgomery'
);
$arrayObject = new ArrayObject($capitals);
foreach ($arrayObject as $state => $capital)
{
printf("The capital of %s is %s
", $state, $capital);
}
// The capital of Arizona is Phoenix
// The capital of Alaska is Juneau
// The capital of Alabama is Montgomery

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

AI Hentai Generator
Generate AI Hentai for free.

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



PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

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,

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

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.

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.
