PHP.mk документација

reset

Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.

function.reset.php PHP.net прокси Преводот се освежува
Оригинал на PHP.net
Патека function.reset.php Локална патека за оваа страница.
Извор php.net/manual/en Оригиналниот HTML се реупотребува и локално се стилизира.
Режим Прокси + превод во позадина Кодовите, табелите и белешките остануваат читливи во истиот тек.
reset

Референца за `function.reset.php` со подобрена типографија и навигација.

function.reset.php

reset

(PHP 4, PHP 5, PHP 7, PHP 8)

resetSet the internal pointer of an array to its first element

= NULL

reset(array|object &$array): mixed

reset() rewinds arrayПоставете го внатрешниот покажувач на низата на првиот елемент

Параметри

array

Влезната низа.

Вратени вредности

's внатрешниот покажувач на првиот елемент и ја враќа вредноста на првиот елемент од низата. false Ја враќа вредноста на првиот елемент од низата, или

Ги ескејпува специјалните знаци во стринг за употреба во SQL изјава

Функцијата враќа прочитани податоци или falseОваа функција може да врати Буловска вредност false, но исто така може да врати и вредност што не е Буловска, а која се проценува како Булови . Ве молиме прочитајте го делот за за повеќе информации. Користете го операторот ===

Дневник на промени

Верзија = NULL
8.1.0 Повикувањето на оваа функција на objects е застарено. Или преобратете го object во array using get_mangled_object_vars() прво, или користете ги методите обезбедени од класа што имплементира Итератор, како на пр. ArrayIterator, наместо тоа.
7.4.0 Инстанци на SPL класите сега се третираат како празни објекти без својства наместо да се повикува Итератор метод со исто име како оваа функција.

Примери

Пример #1 reset() example

<?php

$array
= array('step one', 'step two', 'step three', 'step four');

// by default, the pointer is on the first element
echo current($array) . "<br />\n"; // "step one"

// skip two steps
next($array);
next($array);
echo
current($array) . "<br />\n"; // "step three"

// reset pointer, start again on step one
reset($array);
echo
current($array) . "<br />\n"; // "step one"

?>

Белешки

Забелешка: ако низата е празна. bool false Вратената вредност за празна низа е нераспознатлива од вратената вредност во случај на низа што има false прв елемент. За правилно проверување на вредноста на првиот елемент од низа што може да содржи count() елементи, прво проверете го key() не е nullна низата, или проверете дека reset().

Види Исто така

  • current() - Врати ја тековната ставка во низата
  • each() - Враќа пар од тековниот клуч и вредност од низа и го поместува курсорот на низата
  • end() - Поставете го внатрешниот покажувач на низата на нејзиниот последен елемент
  • next() - Помести го внатрешниот покажувач на низата
  • prev() - Премотајте го внатрешниот покажувач на низата
  • array_key_first() , по повикувањето на

Белешки од корисници 11 белешки

- Го добива првиот клуч на низата
пред 13 години
GOTCHA: If your first element is false, you don't know whether it was empty or not.

<?php

$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.
turabgarip на gmail точка com
пред 4 години
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;

<?php

$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.
milo at mdlwebsolutions dot com
пред 9 години
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.
Bartek Ferek
12 години пред
Note that you can't use pointer here. It will reset the iteration counter in this case.
foreach($array as $key=>&$value) {...} 
 

Use standard foreach instead 
foreach($array as $key=>$value) {...}
Mladen Janjetovic
20 години пред
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
}

}
Alexandre Koriakine
21 години пред
Note that reset() will not affect sub-arrays of multidimensional array.

For example,

<?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>";
        }
    }
    
    reset($arr);

    // 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 $arr[1]
$arr[1][0] = 2
$arr[1][1] = 3
$arr[1][2] = 4
$arr[1][3] = 5
$arr[1][4] = 6
IN $arr[2]
$arr[2][0] = 6
$arr[2][1] = 7
$arr[2][2] = 8
$arr[2][3] = 9
$arr[2][4] = 10
IN $arr[1]
IN $arr[2]
leaetherstrip at inbox dot NOSPAMru
пред 10 години
Info:

Following code gives a strict warning in 5.4.45

      return reset(array_keys($result['node']));

"Strict warning: Only variables should be passed by reference"

So should be:

      $keys = array_keys($result['node']);
      return reset($keys);
arne dot slabbinck at duo dot be
пред 10 години
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.
kendsnyder на gmail точка com
пред 16 години
Don't use `reset()` to get the first value of an associative array. It works great for true arrays but works unexpectedly on Iterator objects. http://bugs.php.net/bug.php?id=38478
arne dot ludwig at posteo dot de
19 години пред
Colin, there`s a better (IMO) way to solve your problem.
<?  
  // ...
  foreach($a as $k => &$d){}   // notice the "&"
  // ...
?>
It`s a new feature in PHP5 to use references in foreach loop. This way PHP isn`t making a copy of the array, so the internal pointer won`t be reset.
m dot lebkowski+php at gmail dot com
19 години пред
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:

<?
$a = array(
    'a' => array(
        'A', 'B', 'C', 'D',
    ),
    'b' => array(
        'AA', 'BB', 'CC', 'DD',
    ),
);

// 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']);

var_dump(key($a['b']));
foreach($a as $k => $d)
{
}
var_dump(key($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.

<?
foreach(array_keys($a) as $k)
{
}
?>

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.
На оваа страница

Автоматски outline од активната документација.

Насловите ќе се појават тука по вчитување.

Попрегледно читање

Примерите, changelog табелите и user notes се визуелно издвоени за да не се губат во долгата содржина.

Брз совет Користи го outline-от Скокни директно на главните секции од активната страница.
Извор Оригиналниот линк останува достапен Кога ти треба целосен upstream context, отвори го PHP.net во нов tab.