prev

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

prev内部の配列ポインタをひとつ前に戻す

説明

prev(array|object &$array): mixed

内部の配列ポインタをひとつ前に戻します。

prev() は、 内部の配列ポインタを進めるのではなく戻すということを除けば next() と同じです。

パラメータ

array

入力の配列。

戻り値

内部の配列ポインタが指している前の場所の配列値を返します。 もう要素がない場合は false を返します。

警告

この関数は論理値 false を返す可能性がありますが、false として評価される値を返す可能性もあります。 詳細については 論理値の セクションを参照してください。この関数の返り値を調べるには ===演算子 を 使用してください。

変更履歴

バージョン 説明
8.1.0 この関数を object に対してコールすることは、推奨されなくなりました。 object に対して最初に get_mangled_object_vars() を使って配列に変換するか、ArrayIterator のような Iterator を実装したクラスのメソッドを使ってください。
7.4.0 SPL クラスのインスタンスは、プロパティを持たない空のオブジェクトのように扱われるようになりました。これより前のバージョンでは、この関数と同じ名前の Iterator のメソッドをコールしていました。

例1 prev() および類似関数の使用例

<?php
$transport
= array('foot', 'bike', 'car', 'plane');
echo
$mode = current($transport), PHP_EOL; // $mode = 'foot';
echo $mode = next($transport), PHP_EOL; // $mode = 'bike';
echo $mode = next($transport), PHP_EOL; // $mode = 'car';
echo $mode = prev($transport), PHP_EOL; // $mode = 'bike';
echo $mode = end($transport), PHP_EOL; // $mode = 'plane';
?>

注意

注意: 配列の先頭でこの関数を実行した結果は、 先頭が boolfalse だった場合と区別できません。 区別するには、prev() 要素の key() 要素が null でないかを確認するようにしてください。

参考

  • current() - 配列内の現在の要素を返す
  • end() - 配列の内部ポインタを最終要素にセットする
  • next() - 配列の内部ポインタを進める
  • reset() - 配列の内部ポインタを先頭の要素にセットする
  • each() - 配列から現在のキーと値のペアを返して、カーソルを進める

add a note

User Contributed Notes 3 notes

up
0
MicroVB INC
11 years ago
This function searches for the closest element in an array by key value, and returns the key/value pair, or false if not found.

<?php
function nearest($array, $value, $exact=false) {
        // Initialize Variables
    $next = false;
    $prev = false;
    $return = false;
    
    if(!isset($array[$value]) && !$exact) {
        // Insert element that doesn't exist so nearest can be found
        $array[$value] = '-';
    }
    
    if($exact && isset($array[$value])) {
                // If exact match found, and searching for exact (not nearest), return result.
        $return = Array($value=>$array[$value]);
    } else {
            // Sort array so injected record is near relative numerics
        ksort($array); // Sort array on key

                // Loop through array until match is found, then set $prev and $next to the respective keys if exist
        while ( !is_null($key = key($array)) ) {
            $val = current($array);
            if($key == $value) {
                prev($array); // Get entry before this one
                $prev = key($array);
                next($array);         // Skip current entry as this was what we were looking for nearest to
                next($array); // Get entry after this one
                $next = key($array);
                break;
            }
            next($array);
        }

        if($prev && $next) {
            if(($long - $prev) > ($next - $long)) {
                                 // Previous is closer
                $return = Array($prev=>$array[$prev]);
            } else {
                                 // Next is closer
                $return = Array($next=>$array[$next]);
            }
        } elseif ($prev || $next) {
            if($prev) {
                                 // Only Previous exists
                $return = Array($prev=>$array[$prev]);
            } elseif ($next) {
                                 // Only Next exists
                $return = Array($next=>$array[$next]);
            }
        }
    }

        // Return resulting Array().   $return is false if nothing matches the closest conditions, or if exact is specified and key does not exist.        
    return $return;
}
?>

Example usage (to lookup the closest color in an array)
<?php
$mycolors= Array(
    5001046=>'Abbey',
    1774596=>'Acadia',
    8171681=>'Acapulco',
    6970651=>'Acorn',
    13238245=>'Aero Blue',
    7423635=>'Affair',
    8803850=>'Afghan Tan',
    13943976=>'Akaroa',
    16777215=>'Alabaster',
    16116179=>'Albescent White',
    10176259=>'Alert Tan',
    30371=>'Allports'
);

// Color to search for in Hex
$color = 'C0C0C0';

// Convert Hex to Long to compare with array() keys
$colorlong = base_convert($color,16,10);

// Check for an exact match
$result = nearest($mycolors, $colorlong, true);
if($result) {
    echo "An exact match was found for #" . $color . " which is called '" . $result[key($result)] . "'";
} else {
    echo "No exact match was found";
}

if(!$result) {
    // Check for closest match
    $result = nearest($mycolors, $colorlong, true);
    if($result) {
        // Match found
        echo "The closest match for #" . $color . " is #" . base_convert(key($result),10,16) . " which is called '" . $result[key($result)] . "'";
    } else {
        // No match found
        echo "No match was found for #" . $color;
    }  
}
?>
up
-1
soapergem at gmail dot com
16 years ago
Here's a slight revision to xmlich02's backwards iteration example. The problem with his/her example is that it will halt if any of the array elements are boolean false, while this version will not.

<?php

end($ar);
while ( !is_null($key = key($ar)) ) {
    $val = current($ar);
    echo "{$key} => {$val}\n";
    prev($ar);
}

?>
up
-2
Mikhail
6 years ago
Function to get element in array, that goes previous your key or false if it not exeists or key doesn't isset in array.

<?php

function previousElement(array $array, $currentKey)
{
    if (!isset($array[$currentKey])) {
        return false;
    }
    end($array);
    do {
        $key = array_search(current($array), $array);
        $previousElement = prev($array);
    }
    while ($key != $currentKey);

    return $previousElement;
}
To Top