prev

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

prevSetzt den internen Arrayzeiger um ein Element zurück

Beschreibung

prev(array|object &$array): mixed

Setzt den internen Zeiger eines Arrays um ein Element zurück.

prev() verhält sich genauso wie next(), abgesehen davon, dass es den Zeiger um ein Element zurücksetzt, nicht nach vorne.

Parameter-Liste

array

Das Eingabe-Array.

Rückgabewerte

Gibt den Wert des Array-Elements vor der Position zurück, auf die der interne Zeiger gerade zeigt. Sind keine Elemente mehr vorhanden, wird false zurückgegeben.

Warnung

Diese Funktion kann sowohl das boolsche false zurückliefern, als auch einen nicht-boolschen Wert, welcher zu false ausgewertet wird. Weitere Informationen entnehmen Sie bitte dem Abschnitt über die boolschen Typen. Benutzen Sie deshalb den === Operator, um den Rückgabewert dieser Funktion zu überprüfen.

Changelog

Version Beschreibung
8.1.0 Bei Objekten ist die Verwendung dieser Funktion veraltet. Stattdessen sollte entweder das Objekt vorher mit get_mangled_object_vars() in ein Array umgewandelt werden oder es sollten die Methoden einer Klasse verwendet werden, die Iterator implementiert, z. B. ArrayIterator.
7.4.0 Instanzen von SPL-Klassen werden nun wie leere Objekte behandelt, die keine Eigenschaften haben, anstatt die Iterator-Methode aufzurufen, die den gleichen Namen wie diese Funktion hat.

Beispiele

Beispiel #1 Beispiel für die Verwendung von prev() und Freunden

<?php
$transport
= array('zu Fuß', 'Fahrrad', 'Auto', 'Flugzeug');
$mode = current($transport); // $mode = 'zu Fuß';
$mode = next($transport); // $mode = 'Fahrrad';
$mode = next($transport); // $mode = 'Auto';
$mode = prev($transport); // $mode = 'Fahrrad';
$mode = end($transport); // $mode = 'Flugzeug';
?>

Anmerkungen

Hinweis: Es ist nicht möglich, den Anfang eines Arrays von einem boolschen false-Element zu unterscheiden. Dieser Fall kann unterschieden werden, indem geprüft wird, ob der key() des prev() Elements nicht null ist.

Siehe auch

  • current() - Liefert das aktuelle Element eines Arrays
  • end() - Positioniert den internen Zeiger eines Arrays auf dessen letztes Element
  • next() - Rückt den internen Arrayzeiger vor
  • reset() - Setzt den internen Zeiger eines Arrays auf sein erstes Element
  • each() - Liefert das aktuelle Schlüssel-Wert-Paar eines Arrays und rückt den Arrayzeiger vor

add a note add a note

User Contributed Notes 4 notes

up
0
MicroVB INC
10 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
0
soapergem at gmail dot com
15 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
-1
Mikhail
5 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;
}
up
-10
MicroVB INC
10 years ago
Some corrections to the previous function.
- When prev() and next() distance is now calculated properly returning the 'closer' one.
- When exact is false, and an item exists with the key searched for, it now returns that entry instead of next/prev closest
- At ends of the array, sometimes when moving past using next() or prev(), it caused results to die. This was corrected.
- Added field to result stating whether the match was 'exact' ('exact'=>true), or nearest ('exact'=>false)

<?php
function nearest($array, $value, $exact=false) {
   
// Initialize Variables
   
$next = false;
   
$prev = false;
   
$return = false;

   
$arr_begin = false;
   
$arr_end = false;
       
   
$exact_match = false;
       
   
    if(
$exact && isset($array[$value])) {
       
// If exact match found, and searching for exact (not nearest), return result.
       
$return = Array($value=>$array[$value]);
       
$exact_match = true;
    } elseif (!
$exact && isset($array[$value])) {
       
// If exact match found, and searching for nearest, return result.
       
$return = Array($value=>$array[$value]);
       
$exact_match = true;
    } else {

        if(!isset(
$array[$value]) && !$exact) {
           
// Insert element that doesn't exist so nearest can be found
           
$array[$value] = '-';
        }
   
       
// Sort array so injected record is near relative numerics
       
ksort($array); // Sort array on key

        // Set start and end keys
       
$arr_begin = key($array);
       
end($array);
       
$arr_end = key($array);
       
reset($array);
       
       
// 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) {
                if(
$value <> $arr_begin) {
                   
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
               
               
if($value <> $arr_end) {
                   
next($array); // Get entry after this one
                   
$next = key($array);
                }
                break;
            }
           
next($array);
        }

        if(
$prev && $next) {
            if((
$value - $prev) < ($next - $value)) {
               
// 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.       
   
if($return) {
        return
$return+Array('exact'=>$exact_match);
    } else {
        return
false;
    }
}
?>

Just to clarify, this function will return either an Array() containing the $key=>$value pair of the result and 'exact'=>(bool) whether the match was exact or not.

To access the $key=>$value pair, can be done as follows :
<?php

    $result
= nearest( ... );  // Just here for clarification of the position for the code that follows.
    
   
if($result) {
       
// Output the Key
       
echo key($result);

       
// Output the Value
       
echo $result( key($result) );

       
// Output if exact match
       
if($result['exact']) {
            echo
'This was an EXACT match';
        } else {
            echo
'This result was found with fuzzy logic';
        }

    } else {

        echo
'No result found';

    }

?>
To Top