Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/css/33.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何将php内部指针设置回数组的第一个元素?_Php_Arrays - Fatal编程技术网

如何将php内部指针设置回数组的第一个元素?

如何将php内部指针设置回数组的第一个元素?,php,arrays,Php,Arrays,我得到了一些存储在下面数组中的数据 <?php $userData = Array ( 'j'=>21, 'temp' =>'Edwin', 'address'=> '1 Old Street', 'age' =>61 ); foreach($userData as $key => $value){ echo "{$key} => {$value}\n"; $index= $key; } ?&

我得到了一些存储在下面数组中的数据

<?php



$userData = Array
(
    'j'=>21,
    'temp' =>'Edwin',
    'address'=> '1 Old Street',
    'age' =>61 
);

foreach($userData as $key => $value){
    echo "{$key} => {$value}\n";
    $index= $key;
}


?>


在使用foreach循环读取数组后,我希望将数组中第一个元素的值存储到变量中?

要将php的内部指针重置为数组中的第一个元素,请调用
reset
函数

就你而言:

    <?php



$userData = Array
(
    'j'=>21,
    'temp' =>'Edwin',
    'address'=> '1 Old Street',
    'age' =>61 
);

foreach($userData as $key => $value){
    echo "{$key} => {$value}\n";
    $index= $key;
}
reset($userData); // Throw away return value
$item = reset($userData); //Keep first element of the array in $item. 

echo $item; 


?>


注意:尝试回显数组echo$userData[0]将返回一个未定义的偏移量

您始终可以使用
[0]
@julekgwa访问数组的第一个元素-而不是像这样的关联数组this@julekgwa当然不是这样。
reset()
将数组指针重置回第一个元素;但是
$firstValue=$userData[array\u shift(array\u keys($userData))
甚至是简单的
$firstValue=$userData[key($userData)]如果数组指针已被重绕