end

(PHP 4, PHP 5, PHP 7)

endУстанавливает внутренний указатель массива на его последний элемент

Описание

mixed end ( array &$array )

end() устанавливает внутренний указатель array на последний элемент и возвращает его значение.

Список параметров

array

Массив. Этот массив передается по ссылке, потому что он модифицируется данной функцией. Это означает что вы должны передать его как реальную переменную, а не как функцию, возвращающую массив, так как по ссылке можно передавать только реальные переменные.

Возвращаемые значения

Возвращает значение последнего элемента или FALSE для пустого массива.

Примеры

Пример #1 Пример использования end()

<?php

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

?>

Смотрите также

  • current() - Возвращает текущий элемент массива
  • each() - Возвращает текущую пару ключ/значение из массива и смещает его указатель
  • prev() - Передвигает внутренний указатель массива на одну позицию назад
  • reset() - Устанавливает внутренний указатель массива на его первый элемент
  • next() - Передвигает внутренний указатель массива на одну позицию вперёд

Коментарии

Автор:
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:

<?php
function array_add(&$array$value) {
$array[] = $value// add an element
end($array); // important!
return key($array);
}
?>
2002-08-28 21:17:30
http://php5.kiev.ua/manual/ru/function.end.html
Автор:
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:

<?php
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)];
}
?>
2002-08-28 21:34:37
http://php5.kiev.ua/manual/ru/function.end.html
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";

?>
2005-10-27 12:02:24
http://php5.kiev.ua/manual/ru/function.end.html
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"
?>
2006-07-11 15:48:15
http://php5.kiev.ua/manual/ru/function.end.html
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.
2009-08-23 20:05:29
http://php5.kiev.ua/manual/ru/function.end.html
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

<?php
//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.
2010-06-07 05:12:19
http://php5.kiev.ua/manual/ru/function.end.html
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".
2010-12-01 17:06:00
http://php5.kiev.ua/manual/ru/function.end.html
If all you want is the last item of the array without affecting the internal array pointer just do the following:

<?php

function endc$array ) { return end$array ); }

$items = array( 'one''two''three' );
$lastItem endc$items ); // three
$current current$items ); // one
?>

This works because the parameter to the function is being sent as a copy, not as a reference to the original variable.
2012-03-01 03:20:46
http://php5.kiev.ua/manual/ru/function.end.html
Автор:
$filename = 'somefile.jpg';

php v5.4 does not support the following statement.
echo end(explode(".", $filename)); // return jpg string

instead you have to split into 2 statements
$file = explode(".", $filename);
echo end ($file);
2013-03-18 12:37:15
http://php5.kiev.ua/manual/ru/function.end.html
I found that the function end() is the best for finding extensions  on file name. This function cleans backslashes and takes the extension of a file.

<?php
private function extension($str){
   
$str=implode("",explode("\\",$str));
   
$str=explode(".",$str);
   
$str=strtolower(end($str));
     return 
$str;
}

// EXAMPLE:
$file='name-Of_soMe.File.txt';
echo 
extension($file); // txt
?>

Very simple.
2014-05-08 19:47:18
http://php5.kiev.ua/manual/ru/function.end.html
Автор:
In case you need add separator at end

$numbers = array('1','2','3','4');
        foreach ($numbers as $number){
            echo $number;
            if (end($numbers) != $number){
                echo ', ';
            }
        }
2016-05-14 20:16:03
http://php5.kiev.ua/manual/ru/function.end.html
Автор:
I found using pathinfo very useful in getting extension of  a file. 
<? Php
  $filename 
dictionary.txt;
   
$ext strtolower(pathinfo($filenamePATHINFO_EXTENSION)) ;

echo 
$ext// txt
?>
2016-10-24 09:16:33
http://php5.kiev.ua/manual/ru/function.end.html
Автор:
Attempting to get the value of a key from an empty array through end() will result in NULL instead of throwing an error or warning becuse end() on an empty array results in false:

<?php

$a 
= ['a' => ['hello' => 'a1','world' => 'a2'],
     
'b' => ['hello' => 'b1','world' => 'b2'],
     
'c' => ['hello' => 'c1','world' => 'c2']
    ];
$b = [];

var_dump(end($a)['hello']);
var_dump(end($b)['hello']);
var_dump(false['hello']);

?>

Results in:

string(2) "c1"
NULL
NULL
2017-07-15 08:55:40
http://php5.kiev.ua/manual/ru/function.end.html
Автор:
<?php
$A
=[1];
print_r($A);
end($A[5]);
print_r($A);
?>

Array
(
    [0] => 1
)
Array
(
    [0] => 1
    [5] => 
)
2018-04-28 19:17:10
http://php5.kiev.ua/manual/ru/function.end.html
To get the first element:

    // Get first item.
    foreach ($array as $item) {
        $first = $item;
        break;
    }
    // $first will have the first element.
2018-11-16 13:12:26
http://php5.kiev.ua/manual/ru/function.end.html

    Поддержать сайт на родительском проекте КГБ