reset
reset() перемещает внутренний указатель массива array к его первому элементу и возвращает значение первого элемента массива.
Список параметров
Возвращаемые значения
Возвращает значение первого элемента массива, или false , если массив пуст.
Эта функция может возвращать как логическое значение false , так и значение не типа boolean, которое приводится к false . За более подробной информацией обратитесь к разделу Булев тип. Используйте оператор === для проверки значения, возвращаемого этой функцией.
Список изменений
| Версия | Описание |
|---|---|
| 8.1.0 | Вызов функции в объекте ( object ) объявлен устаревшим. Либо сначала преобразуйте объект ( object ) в массив ( array ) с помощью функции get_mangled_object_vars() , либо используйте методы, предоставляемые классом, реализующим интерфейс Iterator , например, ArrayIterator . |
| 7.4.0 | Экземпляры классов SPL теперь обрабатываются как пустые объекты, не имеющие свойств, вместо вызова метода Iterator с тем же именем, что и эта функция. |
Примеры
Пример #1 Пример использования reset()
$array = array( ‘первый шаг’ , ‘второй шаг’ , ‘третий шаг’ , ‘четвёртый шаг’ );
// по умолчанию указатель указывает на первый элемент
echo current ( $array ) . «<br />\n» ; // «первый шаг»
// пропускаем два шага
next ( $array );
next ( $array );
echo current ( $array ) . «<br />\n» ; // «третий шаг»
// сбрасываем указатель, тем самым возвращаемся к первому шагу
reset ( $array );
echo current ( $array ) . «<br />\n» ; // «первый шаг»
Примечания
Замечание: Результат использования на пустом массиве будет неотличим от использования массива, первый элемент которого имеет тип bool со значением false . Чтобы правильно проверить значение первого элемента, который может содержать false , можно использовать функцию count() или проверить значение key() , что оно не равно null , после вызова reset() .
Смотрите также
- current() — Возвращает текущий элемент массива
- each() — Возвращает текущую пару ключ/значение из массива и смещает его указатель
- end() — Устанавливает внутренний указатель массива на его последний элемент
- next() — Перемещает указатель массива вперёд на один элемент
- prev() — Передвигает внутренний указатель массива на одну позицию назад
- array_key_first() — Получает первый ключ массива
User Contributed Notes 13 notes
GOTCHA: If your first element is false, you don’t know whether it was empty or not.
$a = array();
$b = array( false , true , true );
var_dump ( reset ( $a ) === reset ( $b )); //bool(true)
?>
So don’t count on a false return being an empty array.
As for taking first key of an array, it’s much more efficient to RESET and then KEY, rather then RESET result of ARRAY_KEYS (as sugested by gardnerjohng at gmail dot com).
<?php
reset ( $someArray );
echo key ( $someArray );
?>
This will give the same result but is much much faster. Larger arrays, better performance. Tested on 100-elements long array with 16 times faster results.
Also it’s good to reset this way the multidimentional arrays:
reset($voo2[‘moder’]);
while (list($key, $value) = each ($voo2[‘moder’])) <
reset($voo2[‘moder’][$key]);
while (list($key1, $value1) = each ($voo2[‘moder’][$key])) <
#do what u want
>
Use standard foreach instead
foreach($array as $key=>$value)
Note that reset() will not affect sub-arrays of multidimensional array.
<?php
$arr = array(
1 => array( 2 , 3 , 4 , 5 , 6 ),
2 => array( 6 , 7 , 8 , 9 , 10 )
);
while(list( $i ,) = each ( $arr ))
<
echo «IN \$arr[ $i ]<br>» ;
while(list( $sub_i , $entry ) = each ( $arr [ $i ]))
<
echo «\$arr[ $i ][ $sub_i ] = $entry <br>» ;
>
>
// Do the same again
while(list( $i ,) = each ( $arr ))
<
echo «IN \$arr[ $i ]<br>» ;
while(list( $sub_i , $entry ) = each ( $arr [ $i ]))
<
echo «\$arr[ $i ][ $sub_i ] = $entry <br>» ;
>
>
?>
will print
In response to gardnerjohng’s note to retrieve the first _key_ of an array:
To retrieve the first _key_ of an array you can use the combination of reset() and key().
<?php
$properties = array(
‘colour’ => ‘grey’ ,
‘flavour’ => ‘rubber’ ,
‘name’ => ‘Mouse Ball’ ,
‘texture’ => ‘rubbery’
);
reset ( $properties );
echo key ( $properties ); // => ‘colour’
?>
I prefer this solution as you don’t have to create the keys array. This should (not measured) improve performance on large arrays.
Following code gives a strict warning in 5.4.45
«Strict warning: Only variables should be passed by reference»
$keys = array_keys($result[‘node’]);
return reset($keys);
Since reset() returns the first «value» of the array beside resetting its internal pointer; it will return different results when it is combined with key() or used separately. Like;
$products = array(
‘biscuits’ => array( ‘biscuit1’ => ‘cobis’ , ‘biscuit2’ => ‘probis’ ),
‘chocolates’ => array( ‘coco1’ => ‘cococ’ , ‘coco2’ => ‘prococ’ ),
);
echo key ( reset ( $products [ ‘biscuits’ ])); // Fatal error
reset ( $products [ ‘biscuits’ ]);
echo key ( $products [ ‘biscuits’ ]); // Will print ‘biscuit1’
?>
This is perfectly normal because in the first method, reset() returned the first «value» of the ‘biscuits’ element which is to be «cbosi». So key(string) will cause a fatal error. While in the second method you just reset the array and didn’t use a returning value; instead you reset the pointer and than extracted the first key of an array.
If your array has more dimensions, it won’t probably cause a fatal error but you will get different results when you combine reset() and key() or use them consecutively.
I had a problem with PHP 5.0.5 somehow resetting a sub-array of an array with no apparent reason. The problem was in doing a foreach() on the parent array PHP was making a copy of the subarrays and in doing so it was resetting the internal pointers of the original array.
The following code demonstrates the resetting of a subarray:
// Set the pointer of $a to ‘b’ and the pointer of ‘b’ to ‘CC’
reset($a);
next($a);
next($a[‘b’]);
next($a[‘b’]);
next($a[‘b’]);
The result of the two var dumps are 3 and 0, respectively. Clearly the internal pointer of $a[‘b’] was reset by doing the foreach loop over $a.
Each time the foreach loop iterated over the ‘a’ and ‘b’ keys of $a it made a copy of $a[‘a’] and $a[‘b’] into $d which resetted the internal pointers of $a[‘a’] and $a[‘b’] despite making no obvious changes.
The solution is instead to iterate over the keys of $a.
and using $a[$k] (or creating an alias of $a[$k] as $d and dealing with the consequences of using aliases).
For the curious, I was implementing the Iterator interface on a dummy object and calling a global object to do the actual iteration (also to cope with PHP’s lack of C-style pointers which when doing a $a = $b on objects would cause the data in $a to be inconsistent with the data in $b when modified). Being that I had many dummy objects representing different data sets I chose to store each data set as a subarray contained within the global object. To make this work each dummy object has to store a key (which can freely be duplicated without problems) that it passes to the global object when rewind, key, current, next, and valid were called on the dummy object.
Unfortunately for me, my key required to be more than just a simple string or number (if it was then it could be used to directly index the subarray of data for that object and problem avoided) but was an array of strings. Instead, I had to iterate over (with a foreach loop) each subarray and compare the key to a variable stored within the subarray.
So by using a foreach loop in this manner and with PHP resetting the pointer of subarrays it ended up causing an infinite loop.
Really, this could be solved by PHP maintaining internal pointers on arrays even after copying.
If you need an easy way to retrieve the first *key* in an array (instead of the value), it can be done like this:
<?php
$properties = array(
‘colour’ => ‘grey’ ,
‘flavour’ => ‘rubber’ ,
‘name’ => ‘Mouse Ball’ ,
‘texture’ => ‘rubbery’
);
# Will output «colour».
echo reset ( array_keys ( $properties ));
?>
Potentially helpful for configuration files that define a sequence of items as an associative array.
I wrote a nice function, which rotates values of array. Very useful for table rows where you have to rotate colors
<?php
function rotate (& $array ) <
$item = current ( $array );
if (! next ( $array )) reset ( $array );
return $item ;
>
?>
Reset Array in PHP
This article will introduce different methods to reset an array in PHP.
Use the array_diff() Function to Reset Array in PHP
In PHP, we can use the array_diff() function to reset an array. This function computes the difference of a given array with another array. The correct syntax to use this function is as follows.
The program that clears array values is as follows.
Use the unset() Function to Reset an Array in PHP
We will use the unset() function to clear array values. The unset() functions resets a variable. The correct syntax to use this function is as follows.
This function returns nothing.
The program below shows the way by which we can use the unset() function to clear array values in PHP.
PHP reset() function
In this article, you will learn how to reset the internal pointer of an array. By resetting it means to move the pointer to point to the first element of the array which is the default behavior of the pointer. The reset() function perform this functionality.
What is the syntax of the reset() function in PHP?
| Parameter | Details |
|---|---|
| array | The array to reset the internal pointer of – Required |
PHP reset() function
Examples of reset() function
Example 1. Get the current, next value of the array, and then check the pointer after resetting it.
Example 2. In this example, you will find all the methods related to the reset method category. These methods work with the internal pointer of the arrays.
Как обнулить массив в php
You can reset array values or clear the values very easily in PHP. There are two methods to reset the array which are discussed further in this article.
Methods:
-
Function Function
Method 1: unset() function: The unset() function is used to unset a specified variable or entire array.
Syntax:
Parameters:
- $variable: This parameter is required, it is the variable that is needed to be unset.
Return Value: This function does not return any value.
Output:
Method 2: array_diff() function: The array_diff() function accepts two or more arguments and returns an array containing values from the first array which are not present in other arrays.
Syntax:
Parameters: The function can take any number of arrays as parameters needed to be compared.
Return Value: This function compares the first array in parameters with the rest of the arrays and returns an array containing all the entries from $array1 that are not present in any of the other arrays.