PHP Doku:: Positioniert den internen Zeiger eines Arrays auf dessen letztes Element - function.end.html

Verlauf / Chronik / History: (1) anzeigen

Sie sind hier:
Doku-StartseitePHP-HandbuchFunktionsreferenzVariablen- und typbezogene ErweiterungenArraysArray Funktionenend

Ein Service von Reinhard Neidl - Webprogrammierung.

Array Funktionen

<<each

extract>>

end

(PHP 4, PHP 5)

endPositioniert den internen Zeiger eines Arrays auf dessen letztes Element

Beschreibung

mixed end ( array &$array )

end() rückt den internen Zeiger von array bis zum letzten Element vor, und gibt dessen Wert zurück.

Parameter-Liste

array

Das Array.

Rückgabewerte

Gibt den Wert des letzten Arrayelements zurück oder FALSE bei einem leeren Array.

Beispiele

Beispiel #1 end() example

<?php

$fruits 
= array('apple''banana''cranberry');
echo 
end($fruits); // cranberry

?>

Siehe auch

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


16 BenutzerBeiträge:
- Beiträge aktualisieren...
Tim C
16.12.2010 16:41
An easy (and correct) way to get the last key:
$lastkey = array_pop(array_keys($arr));
franz at develophp dot org
2.12.2010 0:06
It's interesting to note that when creating an array with numeric keys in no particular order, end() will still only return the value that was the last one to be created. So, if you have something like this:

    <?php
    $a
= array();
   
$a[1] = 1;
   
$a[0] = 0;
    echo
end($a);
   
?>

This will print "0".
laurence at crazypillstudios dot com
7.06.2010 11:12
//fixing errors in last post...oops

//this is a function to move items in an array up or down
//in the array. it is done by breaking the array into two
//separate arrays and then have a loop creates the final array
//adding the item we want to move when the counter is equal
//to the new position we established
//the array key, position and direction were passed via a query string

//parameters
//$array- the array you are modifying
//$keytomove - the key of the item you wish to move
//$pos - the current position of the item: used a count($array) function
//and then loop with incrementing integer to add the position to the up //or down button
//$dir - the direction you want to move it - "up"/"dn"

function change_pos($array, $keytomove, $pos, $dir){
    //count the original number of rows
    $count = count($array);
    //set the integer we will use to place the moved item
    if($dir=="up"){
        if($pos==1){
            //if the item is already first and we try moving it up
            //we send it to the end of the array
            $change = $count;
        }else{
            //anywhere else it just moves back one closer to the start of the array
            $change = $pos-1;
        }
    }
    //do the same for the down button
    if($dir=="dn"){
        if($pos==$count){
            $change = 1;
        }else{
            $change = $pos+1;
        }
    }       
    //copy the element that you wish to move
    $move = $array[$keytomove];   
    //delete the original from the main array
    unset($array[$keytomove]);   
    //create an array of the names of the values we
    //are not moving
    $preint = 1;
    foreach($array as $c){       
        $notmoved["{$preint}"] = $c['name'];       
    $preint++;
    }   
    //loop through all the elements
    $int = 1;
    while($int<=$count){   
        //dynamically change the key of the unmoved item as we increment the counter
        $notmovedkey = $notmoved["$int"];
        //when the counter is equal to the position we want
        //to place the moved entry we pump it into a new array
        if($int==$change){
            $neworder["{$keytomove}"] = $move;
        }
        //add all the other array items if the position number is not met and
        //resume adding them once the moved item is written
        if($contkey!=""){
            $neworder["{$notmovedkey}"] = $array["{$notmovedkey}"];           
        }
    $int++;
    }
   
    return($neworder);
}

This is not too elegant but it works.
laurence at crazypillstudios dot com
7.06.2010 11:10
//this is a function to move items in an array up or down
//in the array. it is done by breaking the array into two
//separate arrays and then have a loop creates the final array
//adding the item we want to move when the counter is equal
//to the new position we established
//the array key, position and direction were passed via a query string

//parameters
//$array- the array you are modifying
//$keytomove - the key of the item you wish to move
//$pos - the current position of the item: used a count($array) function
//and then loop with incrementing integer to add the position to the up //or down button
//$dir - the direction you want to move it - "up"/"dn"

function change_pos($array, $keytomove, $pos, $dir){
    //count the original number of rows
    $count = count($array);
    //set the integer we will use to place the moved item
    if($dir=="up"){
        if($pos==1){
            //if the item is already first and we try moving it up
            //we send it to the end of the array
            $change = $count;
        }else{
            //anywhere else it just moves back one closer to the start of the array
            $change = $pos-1;
        }
    }
    //do the same for the down button
    if($dir=="dn"){
        if($pos==$count){
            $change = 1;
        }else{
            $change = $pos+1;
        }
    }       
    //copy the element that you wish to move
    $move = $array[$keytomove];   
    //delete the original from the main array
    unset($array[$keytomove]);   
    //create an array of the names of the values we
    //are not moving
    $preint = 1;
    foreach($array as $c){       
        $notmoved["{$preint}"] = $c['name'];       
    $preint++;
    }   
    //loop through all the elements
    $int = 1;
    while($int<=$count){   
        //dynamically change the key of the unmoved item as we increment the counter
        $notmovedkey = $notmoved["$int"];
        //when the counter is equal to the position we want
        //to place the moved entry we pump it into a new array
        if($int==$change){
            $neworder["{$keytomove}"] = $move;
        }
        //add all the other array items if the position number is not met and
        //resume adding them once the moved item is written
        if($contkey!=""){
            $neworder["{$contkey}"] = $array["{$contkey}"];           
        }
    $int++;
    }
   
    return($neworder);
}

This is not too elegant but it works.
Sam Yong - hellclanner at live dot com
24.08.2009 2:05
Take note that end() does not recursively set your multiple dimension arrays' pointer to the end.

Take a look at the following:
<?php

// create the array for testing
$a = array();
$i = 0;
while(
$i++ < 3){
$a[] = array(dechex(crc32(mt_rand())),dechex(crc32('lol'.mt_rand())));
}

// show the array tree
echo '<pre>';var_dump($a);

// set the pointer of $a to the end
end($a);

// get the current element of $a
var_dump(current($a));
// get the current element of the current element of $a
var_dump(current(current($a)));

?>

You will notice that you probably get something like this:

array(3) {
  [0]=>
  array(2) {
    [0]=>
    string(8) "764d8d20"
    [1]=>
    string(8) "85ee186d"
  }
  [1]=>
  array(2) {
    [0]=>
    string(8) "c8c72466"
    [1]=>
    string(8) "a0fdccb2"
  }
  [2]=>
  array(2) {
    [0]=>
    string(8) "3463a31b"
    [1]=>
    string(8) "589f6b63"
  }
}

array(2) {
  [0]=>
  string(8) "3463a31b"
  [1]=>
  string(8) "589f6b63"
}

string(8) "3463a31b"

The array elements' pointer are still at the first one as current. So do take note.
admin at nabito dot net
6.08.2008 9:04
This is simple way how to get file extension.

<?php
$filename
= 'somefile.jpg';
echo
end(explode(".", $filename)); // return jpg string

$filename = 'the_another_file.html';
echo
end(explode(".", $filename)); // return html string
?>
Sven Arduwie
15.05.2007 22:43
RE: mika dot stenberg at helsinki dot fi
Your function array_set_current is flawed:
function array_set_current(&$array, $key){
   reset($array);
   while(current($array)){
       if(key($array) == $key){
           break;
       }
       next($array);
   }
}

Notice that current() cannot distinguish the end of an array from a boolean FALSE element value. For example, try this:
    $array = array(false, 'This', 'is', 'a', 'test');
    array_set_current($array, 3);
    var_dump(current($array));

This will work:
    function array_set_current(&$array, $key) {
        reset($array);
        foreach ($array as $value) {
            if (key($array) === $key) {
                break;
            }
        }
    }

Also, I prefer key($array) === $key over key($array) == $key.
egingell at sisna dot com
6.05.2007 20:40
Posted by johnny at west dot net
03-Nov-2006 06:45

>> An easier way to get the last key:
>> $lastkey = end(array_keys($arr));

As stated in a previous note, this may not function as expected (or at all) as end() takes the parameter by reference and you cannot pass a function call by reference.
johnny at west dot net
3.11.2006 15:45
An easier way to get the last key:
$lastkey = end(array_keys($arr));
jasper at jtey dot com
11.07.2006 21:48
This function returns the value at the end of the array, but you may sometimes be interested in the key at the end of the array, particularly when working with non integer indexed arrays:

<?php
// Returns the key at the end of the array
function endKey($array){
 
end($array);
 return
key($array);
}
?>

Usage example:
<?php
$a
= array("one" => "apple", "two" => "orange", "three" => "pear");
echo
endKey($a); // will output "three"
?>
Flavio Ventura
29.11.2005 17:02
In some previous post you can use

current($array)

 instead of

$array[key($array)]

I think it's more self-explaining.
ken at expitrans dot com
27.10.2005 18:02
Please note that from version 5.0.4 ==> 5.0.5 that this function now takes an array. This will possibly break some code for instance:

<?php

echo ">> ".end(array_keys(array('x' => 'y')))."\n";

?>

which will return "Fatal error: Only variables can be passed by reference" in version <= 5.0.4 but not in 5.0.5.

If you run into this problem with nested function calls, then an easy workaround is to assign the result from array_keys (or whatever function) to an intermediary variable:

<?php

$x
= array_keys(array('x' => 'y'));
echo
">> ".end($x)."\n";

?>
mika dot stenberg at helsinki dot fi
11.08.2005 15:24
Here's something useful with arrays that I did: change an items position up or down in array. Thanks to previous posters for some useful functions (included):

// $mode -1 (negat) moves the item down, +1 (pos) moves the item up
// I used this because i parsed the mode from the query string
// You get the picture though
// $from_id points which item to move

function change_pos($array, $from_id, $mode){

// get hold of the beginning and the end
$start = first($array);
$end = last($array);

reset($array);

// find the position in an array
array_set_current($array, $from_id);

// remember the old value
$temp = $archive[ $from_id ];

// move down

if ($uusi_id < 0){
 
 
    if (key($array) != $end) {

            $array[ $from_id ] = next($array);
            $array[key($aray)] = $temp;
          }
    else echo "Couldnt move it!";
}

// move up
else if ( key($array) != $start ) {

    $array[ $from_id ] = prev($array);
    $array[key($array)] = $temp;
    save($array);
    }
else echo "Couldnt do it !";

}

function array_set_current(&$array, $key){
   reset($array);
   while(current($array)){
       if(key($array) == $key){
           break;
       }
       next($array);
   }
}

function first(&$array) {
if (!is_array($array)) return null;
if (!count($array)) return null;
reset($array);
return key($array);
}

function last(&$array) {
if (!is_array($array)) return null;
if (!count($array)) return null;
end($array);
return key($array);
}

12.05.2005 10:21
Fix for unknown writer of 29-aug-2002.
If you need to get a reference to the first or last element of an array, use these functions:

    function &first(&$array) {
        if (!is_array($array))
            return null;
        if (!count($array))
            return false; // like reset()
        reset($array);
        return $array[key($array)];
    }
       
    function &last(&$array) {
        if (!is_array($array))
            return null;
        if (!count($array))
            return false; // like end()
        end($array);
        return $array[key($array)];
    }

Example (watch out - use as &last() and &first()):

$a = array( 0 => 'less', 10 => 'ten', 20 => ' more');

if ($first = & first($a)) // not false or null
    $first = 'nothing';
if ($last = & last($a)) // not false or null
    $last = 'double';

Now $a is array( 0 => 'nothing', 10 => 'ten', 20 => ' double')

29.08.2002 3:34
If you need to get a reference on the first or last element of an array, use these functions because reset() and end() only return you a copy that you cannot dereference directly:

function first(&$array) {
if (!is_array($array)) return &$array;
if (!count($array)) return null;
reset($array);
return &$array[key($array)];
}

function last(&$array) {
if (!is_array($array)) return &$array;
if (!count($array)) return null;
end($array);
return &$array[key($array)];
}

29.08.2002 3:17
When adding an element to an array, it may be interesting to know with which key it was added. Just adding an element does not change the current position in the array, so calling key() won't return the correct key value; you must first position at end() of the array:

function array_add(&$array, $value) {
$array[] = $value; // add an element
end($array); // important!
return key($array);
}



PHP Powered Diese Seite bei php.net
The PHP manual text and comments are covered by the Creative Commons Attribution 3.0 License © the PHP Documentation Group - Impressum - mail("TO:Reinhard Neidl",...)