如何在PHP中获取数组的第一个元素?

在本文中,我们将看到如何在PHP中访问数组的第一个元素,并通过示例了解它们的实现。主要有三种类型 PHP中的数组 可用于从数组中提取元素的:

null
  • 索引数组:它是一个带有数字键的数组。它基本上是一个数组,其中每个键都与自己的特定值相关联。
  • 关联数组 :用于存储键值对。
  • 多维数组 :它是一种数组类型,在每个索引处存储另一个数组,而不是单个元素。换句话说,将多维数组定义为数组的数组。

在PHP中,有几种方法可以获取数组的第一个元素。有些方法正在使用 foreach循环 ,重置功能, 数组切片函数 , 数组_值 , 反向排列 ,还有更多。我们将讨论按顺序访问数组第一个元素的不同方法。

通过直接访问第0个索引:

PHP

<?php
// PHP program to access the first
// element of the array
$array = array ( 'geeks' , 'for' , 'computer' );
echo $array [0];
?>


输出:

geeks

使用 foreach循环 : foreach构造同时适用于数组和对象。foreach循环在一个元素数组上迭代,执行过程简化,完成循环的时间相对缩短。

语法:

foreach( $array as $key => $element) {
    // PHP Code to be executed
}

例子: 这个例子演示了PHP中的foreach循环。

PHP

<?php
// PHP program to access the first
// element of the array
$array = array (
33 => 'geeks' ,
36 => 'for' ,
42 => 'computer'
);
foreach ( $array as $name ) {
echo $name ;
// Break loop after first iteration
break ;
}
?>


输出:

geeks

使用 reset()函数 : 函数的作用是将数组的内部指针移动到第一个元素。

语法:

reset($array)

例子: 这个例子说明了 重置() 函数,该函数有助于将任何数组的内部指针移动到该数组的第一个元素。

PHP

<?php
// PHP program to access the first
// element of the array
$array = array (
33 => 'geeks' ,
36 => 'for' ,
42 => 'computer'
);
echo reset( $array );
?>


输出:

geeks

使用 array_slice()函数 : array_slice()返回由offset和length参数指定的数组元素序列。

语法:

array array_slice ( array $array, int $offset [, int $length = NULL [, 
                                        bool $preserve_keys = FALSE ]] )

例子: 这个例子说明了 数组_切片() 函数,根据用户的选择,通过切片获取数组的一部分。

PHP

<?php
// PHP program to access the first
// element of the array
$array = array (
33 => 'geeks' ,
36 => 'for' ,
42 => 'computer'
);
echo array_slice ( $array , 0, 1)[0];
?>


输出:

geeks

使用 array_values()函数 : 此函数从另一个数组返回一个值数组,该数组可能包含键值对或仅包含值。

语法:

array array_values ( array $array )

例子: 本例介绍了array_values()函数的用法。

PHP

<?php
// PHP program to access the first
// element of the array
$array = array (
33 => 'geeks' ,
36 => 'for' ,
42 => 'computer'
);
echo array_values ( $array )[0];
?>


输出:

geeks

使用 数组_pop()函数 : 此函数用于将元素从数组末尾弹出。

语法:

mixed array_pop ( array &$array )

默认情况下 数组_reverse() 函数将重置所有数字数组键以从零开始计数,而文字键将保持不变,除非第二个参数preserve_keys指定为TRUE。不建议使用这种方法,因为在获取第一个值之前,它可能会在较大的阵列上进行不必要的较长处理,以反转它们。

例子: 本例介绍了array_pop函数的使用。

PHP

<?php
// PHP program to access the first
// element of the array
$array = array (
33 => 'geeks' ,
36 => 'for' ,
42 => 'computer'
);
$arr = array_reverse ( $array );
echo array_pop ( $arr );
?>


输出:

geeks

PHP是一种专门为web开发设计的服务器端脚本语言。通过以下步骤,您可以从头开始学习PHP PHP的教程 PHP示例 .

© 版权声明
THE END
喜欢就支持一下吧
点赞7 分享