搜索

PHP 中的数组

Aug 29, 2024 pm 12:42 PM
php

下面的文章《PHP 中的数组》提供了在 PHP 中创建数组的概述。数组是类似数据类型的集合。数组在单个变量中存储多个值。当变量也可以存储值时,为什么需要数组呢?答案是因为存储有限数据的值(例如数字5的计数)是可能的,但是当计数增加到例如100或200时,我们需要在100个变量中存储100个值,这有点困难;因此,我们将其存储在一个数组中。这就是使用数组的原因。

广告 该类别中的热门课程 PHP 开发人员 - 专业化 | 8 门课程系列 | 3次模拟测试

开始您的免费软件开发课程

网络开发、编程语言、软件测试及其他

如何在 PHP 中创建数组?

语法:

variablename = array();

或者

variablename[i] = value;

其中变量名是变量的名称,i是键,或者索引值是元素值。

创建数组的示例

$colors = array("Red","Green","Blue");

为了计算数组的长度,我们使用 count 关键字。

$length = count($colors); // output is 3

数组中的每个值称为数组的一个元素。数组索引从0开始。数组中最后一个元素的索引是数组总长度减1。

在上面给出的示例中,Red 的索引为 0,Green 为 1,Blue 为 2。因此,借助索引或键访问数组变得更容易。为了获取数组每个索引处的值,我们循环遍历给定的数组。要循环数组,我们使用 foreach 循环或 for 循环。

数组在 PHP 中如何工作?

像 foreach 和 for 这样的循环用于循环遍历数组。每个数组都有从 0 开始的索引,依此类推:

PHP 中的数组类型

PHP中有三种类型的数组;让我们详细了解每种类型的数组:

  1. 数字或索引数组
  2. 关联数组
  3. 多维数组
1.数值数组

在此数组类型中,索引始终是数字,它不能是字符串。相反,它可以存储任意数量的元素和任意类型的元素。

语法:

variable name = array("value1","value2","value3","value4")

代码:

<?php //Example to demonstrate numeric array
$input = array("Apple", "Orange", "Banana", "Kiwi");
//Here, to get these values we will write like
echo $input[0] . "\n"; // will give Apple
echo $input[1] . "\n"; // will give Orange
echo $input[2] . "\n"; // will give Banana
echo $input[3] . "\n"; // will give Kiwi
// To get the length of array we will use count
echo "The count of the array is " . count($input); // will give 4
echo "\n";
//To print the array we can use
print_r($input);
?>

输出:

PHP 中的数组

或者

声明数值数组的另一种方法是以下程序。在这个程序中,我们还将看到修改和打印值。

代码:

<?php //Example to demonstrate numeric array in another way
$input[0] = "Apple";
$input[1] = "Orange";
$input[2] = "Banana";
$input[3] = "Kiwi";
// To get Kiwi we will write like
echo $input[3]."<br>"; // will give Kiwi
//To modify Orange value
$input[1] = "Mango";
// Now echo $input[1] will give Mango
echo $input[1]."<br>"; // Mango
//To print the array we can use
print_r($input);
?>

输出:

PHP 中的数组

现在我们将学习如何使用for循环来遍历数组

代码:

<?php //Example to demonstrate for loop on a numeric array
//declaring the array
$input = array("Apple", "Orange", "Banana", "Kiwi", "Mango");
//the for loop to traverse through the input array
for($i=0;$i<count($input); $i++) {
echo $input[$i];
echo "<br>";
}
?>

输出:

PHP 中的数组

2.关联数组

这个数组是键值对的形式,其中键是数组的索引,值是数组的元素。

语法:

$input = array("key1"=>"value1",
"key2"=>"value2",
"key3"=>"value3",
"key4"=>"value4");

或者

不使用数组关键字声明关联数组的另一种方法

$input[$key1] = $value1;
$input[$key2] = $value2;
$input[$key3] = $value3;
$input[$key4] = $value4;

代码:

<?php //Example to demonstrate associative array
//declaring an array
$input = array(
"Jan"=>31,
"Feb"=>28,
"Mar"=>31,
"Apr"=>30);
// the for loop to traverse through the input array
foreach($input as $in) {
echo $in."<br>";}
?>

输出:

PHP 中的数组

3.多维数组

这个数组是数组的数组,其中数组的值包含数组。

语法:

$input =array(
array('value1', 'value2', 'value3'),
array('value4', 'value5', 'value6'),
array('value7', 'value8', 'value9'));,

代码:

<?php //Example to demonstrate multidimensional array
// declaring a multidimensional array
$input = array ("colors"=>array ("Red", "Green", "Blue"),
"fruits"=>array ("Apple", "Orange", "Grapes"),
"cars"=>array ("Skoda", "BMW", "Mercedes")
);
//the foreach loop to traverse through the input array
foreach($input as $key=>$value) {
echo $key .'--'. "<br>";
foreach($value as $k=>$v)
{echo $v ." ";}
echo "<br>";
}
?>

输出:

PHP 中的数组

或者

关联数组中的多维数组

代码:

<?php //Example to demonstrate multidimensional array
// declaring a multidimensional array
$input = array(
"The_Alchemist" => array (
"author" => "Paulo Coelho",
"type" => "Fiction",
"published_year" => 1988),
"Managing_Oneself" => array(
"author" => "Peter Drucker",
"type" => "Non-fiction",
"published_year" => 1999
),"Measuring_the_World" => array(
"author" => "Daniel Kehlmann",
"type" => "Fiction",
"published_year" => 2005
));
//the foreach loop to traverse through the input array
//foreach to loop the outer array
foreach($input as $book) {
echo "<br>";
// foreach to loop the inner array
foreach($book as $key=>$value)
{
echo $key." ". $value. "<br>";}
}?>

输出:

PHP 中的数组

PHP 中的数组方法

以下是 PHP 中数组的方法:

1. Count() 方法

该方法用于统计数组中元素的数量。

语法:

Count(array, mode)

需要计数的地方,模式是可选的。

代码:

<?php //Example to demonstrate use of in_array method
//declaring associative array
$input=array('English','Hindi','Marathi');
//counting the number of elements in the given array
echo count($input);
?>

输出:

PHP 中的数组

2. Array_walk() 方法

该方法接受两个参数作为输入;第一个参数是输入数组,第二个参数是声明的函数的名称。该方法用于循环遍历数组中的每个元素。

语法:

array_walk(array, function_name, parameter...)

其中需要数组的地方需要 function_name

参数是可选的

代码:

<?php //Example to demonstrate use of array_walk method
//creating a function to print the key and values of the given array
function fun($val, $k) {
echo $k. " --" .$val ."\n";
}
// declaring associative array
$input=array("e"=>'English', "h"=>'Hindi', "m"=>'Marathi');
//passing this array as a first parameter to the function
// array_walk,
//second paramter as the name of the function being called
array_walk($input,"fun");
?>

Output:

PHP 中的数组

3. In_array() method

This method performs a search on the array, whether the given array contains a particular value or not. If found or not found, it will execute respective if, else block

Syntax:

in_array(search_value, array_name)

Where both the parameters are required

Code:

<?php //Example to demonstrate use of in_array method
// declaring associative array
$input=array('English','Hindi','Marathi', "Maths", "Social Science");
// using in_array to find Maths in given array
if(in_array("Maths", $input)) {
echo "Found Maths in the given array";
}
else
{
echo "Did not find Maths in the given array";
}
?>

Output:

PHP 中的数组

4. Array_pop() method

This method removes the last element from the given array.

Syntax

array_pop(array_name)

Code:

<?php //Example to demonstrate use of array_pop method
// declaring array
$input=array('English','Hindi','Marathi');
// before using array_pop on the given array
print_r($input);
// after using array_pop method on the given array
array_pop($input);
echo "\n ";
print_r($input);
?>

Output:

PHP 中的数组

5. Array_push() method

This method adds given elements at the end of the array.

Syntax:

array_push(array_name, value1, value2, ...)

Code:

<?php //Example to demonstrate use of array_push method
// declaring array
$input=array('English','Hindi','Marathi');
// before using array_push on the given array
print_r($input);
// after using array_push method on the given array
array_push($input, "Economics", "Maths", "Social Science");
echo "\n";
//printing the array
print_r($input);
?>

Output:

PHP 中的数组

6. Array_shift() method

This method removes and returns the first element of the array.

Syntax: 

array_shift(array_name)

Code:

<?php //Example to demonstrate use of array_push method
// declaring array
$input=array('English','Hindi','Marathi');
// before using array_shift on the given array
print_r($input);
echo "\n";
// after using array_shift method on the given array
echo array_shift($input);
?>

Output:

PHP 中的数组

7. Array_unshift() method

This method inserts given elements into the beginning of the array.

Syntax:

array_unshift(array_name, value1, value2,…)

Code:

<?php //Example to demonstrate use of array_push method
// declaring array
$input=array('English','Hindi','Marathi');
// before using array_unshift on the given arrayprint_r($input);
echo "\n";
// after using array_unshift method on the given array
array_unshift($input, "Economics");
print_r($input);
?>

Output:

PHP 中的数组

8. Array_reverse() method

This method is used to reverse the elements of the array.

Syntax:

array_reverse(array_name, preserve)

where array_name is required,

preserve is optional

Code:

<?php //Example to demonstrate use of in_array method
// declaring associative array
$input=array("e"=>'English',"h"=>'Hindi',"m"=>'Marathi');
// array before reversing the elements
print_r($input);
echo "\n";
// printing the reverse
// array after reversing the elements
print_r(array_reverse($input));
?>

Output:

PHP 中的数组

Conclusion

This article covers all levels of concepts, simple and complex, of the topic arrays in PHP. I hope you found this article interesting and informative for the learning purpose.

以上是PHP 中的数组的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
使用数据库存储会话的优点是什么?使用数据库存储会话的优点是什么?Apr 24, 2025 am 12:16 AM

使用数据库存储会话的主要优势包括持久性、可扩展性和安全性。1.持久性:即使服务器重启,会话数据也能保持不变。2.可扩展性:适用于分布式系统,确保会话数据在多服务器间同步。3.安全性:数据库提供加密存储,保护敏感信息。

您如何在PHP中实现自定义会话处理?您如何在PHP中实现自定义会话处理?Apr 24, 2025 am 12:16 AM

在PHP中实现自定义会话处理可以通过实现SessionHandlerInterface接口来完成。具体步骤包括:1)创建实现SessionHandlerInterface的类,如CustomSessionHandler;2)重写接口中的方法(如open,close,read,write,destroy,gc)来定义会话数据的生命周期和存储方式;3)在PHP脚本中注册自定义会话处理器并启动会话。这样可以将数据存储在MySQL、Redis等介质中,提升性能、安全性和可扩展性。

什么是会话ID?什么是会话ID?Apr 24, 2025 am 12:13 AM

SessionID是网络应用程序中用来跟踪用户会话状态的机制。1.它是一个随机生成的字符串,用于在用户与服务器之间的多次交互中保持用户的身份信息。2.服务器生成并通过cookie或URL参数发送给客户端,帮助在用户的多次请求中识别和关联这些请求。3.生成通常使用随机算法保证唯一性和不可预测性。4.在实际开发中,可以使用内存数据库如Redis来存储session数据,提升性能和安全性。

您如何在无状态环境(例如API)中处理会议?您如何在无状态环境(例如API)中处理会议?Apr 24, 2025 am 12:12 AM

在无状态环境如API中管理会话可以通过使用JWT或cookies来实现。1.JWT适合无状态和可扩展性,但大数据时体积大。2.Cookies更传统且易实现,但需谨慎配置以确保安全性。

您如何防止与会议有关的跨站点脚本(XSS)攻击?您如何防止与会议有关的跨站点脚本(XSS)攻击?Apr 23, 2025 am 12:16 AM

要保护应用免受与会话相关的XSS攻击,需采取以下措施:1.设置HttpOnly和Secure标志保护会话cookie。2.对所有用户输入进行输出编码。3.实施内容安全策略(CSP)限制脚本来源。通过这些策略,可以有效防护会话相关的XSS攻击,确保用户数据安全。

您如何优化PHP会话性能?您如何优化PHP会话性能?Apr 23, 2025 am 12:13 AM

优化PHP会话性能的方法包括:1.延迟会话启动,2.使用数据库存储会话,3.压缩会话数据,4.管理会话生命周期,5.实现会话共享。这些策略能显着提升应用在高并发环境下的效率。

什么是session.gc_maxlifetime配置设置?什么是session.gc_maxlifetime配置设置?Apr 23, 2025 am 12:10 AM

thesession.gc_maxlifetimesettinginphpdeterminesthelifespanofsessiondata,setInSeconds.1)它'sconfiguredinphp.iniorviaini_set().2)abalanceIsiseededeedeedeedeedeedeedto to to avoidperformance andununununununexpectedLogOgouts.3)

您如何在PHP中配置会话名?您如何在PHP中配置会话名?Apr 23, 2025 am 12:08 AM

在PHP中,可以使用session_name()函数配置会话名称。具体步骤如下:1.使用session_name()函数设置会话名称,例如session_name("my_session")。2.在设置会话名称后,调用session_start()启动会话。配置会话名称可以避免多应用间的会话数据冲突,并增强安全性,但需注意会话名称的唯一性、安全性、长度和设置时机。

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

SublimeText3 英文版

SublimeText3 英文版

推荐:为Win版本,支持代码提示!

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

mPDF

mPDF

mPDF是一个PHP库,可以从UTF-8编码的HTML生成PDF文件。原作者Ian Back编写mPDF以从他的网站上“即时”输出PDF文件,并处理不同的语言。与原始脚本如HTML2FPDF相比,它的速度较慢,并且在使用Unicode字体时生成的文件较大,但支持CSS样式等,并进行了大量增强。支持几乎所有语言,包括RTL(阿拉伯语和希伯来语)和CJK(中日韩)。支持嵌套的块级元素(如P、DIV),

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境