Как найти последний элемент php

The many answers in this thread present us with many different options. To be able to choose from them I needed to understand their behavior and performance. In this answer I will share my findings with you, benchmarked against PHP versions 5.6.38, 7.2.10 and 7.3.0RC1 (expected Dec 13 2018).

The options (<<option code>>s) I will test are:

  • option .1. $x = array_values(array_slice($array, -1))[0]; (as suggested by rolacja)
  • option .2. $x = array_slice($array, -1)[0]; (as suggested by Stoutie)
  • option .3. $x = array_pop((array_slice($array, -1))); (as suggested by rolacja)
  • option .4. $x = array_pop((array_slice($array, -1, 1))); (as suggested by Westy92)
  • option .5. $x = end($array); reset($array); (as suggested by Iznogood)
  • option .6. $x = end((array_values($array))); (as suggested by TecBrat)
  • option .7. $x = $array[count($array)-1]; (as suggested by Mirko Pagliai)
  • option .8. $keys = array_keys($array); $x = $array[$keys[count($keys)-1]]; (as suggested by thrau)
  • option .9. $x = $array[] = array_pop($array); (as suggested by user2782001)
  • option 10. $x = $array[array_key_last($array)]; (as suggested by Quasimodo’s clone ; available per PHP 7.3)

(functions mentioned: array_key_last , array_keys , array_pop , array_slice , array_values , count , end , reset)

The test inputs (<<input code>>s) to combine with:

  • null = $array = null;
  • empty = $array = [];
  • last_null = $array = ["a","b","c",null];
  • auto_idx = $array = ["a","b","c","d"];
  • shuffle = $array = []; $array[1] = "a"; $array[2] = "b"; $array[0] = "c";
  • 100 = $array = []; for($i=0;$i<100;$i++) { $array[] = $i; }
  • 100000 = $array = []; for($i=0;$i<100000;$i++) { $array[] = $i; }

For testing I will use the 5.6.38, 7.2.10 and 7.3.0RC1 PHP docker containers like:

sudo docker run -it --rm php:5.6.38-cli-stretch php -r '<<<CODE HERE>>>'

Each combination of the above listed <<option code>>s and <<input code>>s will be run on all versions of PHP. For each test run the following code snippet is used:

<<input code>>  error_reporting(E_ALL);  <<option code>>  error_reporting(0); $before=microtime(TRUE); for($i=0;$i<100;$i++){echo ".";for($j=0;$j<100;$j++){  <<option code>>  }}; $after=microtime(TRUE); echo "n"; var_dump($x); echo round(($after-$before)/(100*100)*1000*1000*1000);

For each run this will var_dump the last retrieved last value of the test input and print the average duration of one iteration in femtoseconds (0.000000000000001th of a second).

The results are as follows:

/==========================================================================================================================================================================================================================================================================================================================================================================================================================
||                                                                      ||                            T  E  S  T     I  N  P  U  T     -     5  .  6  .  3  8                            ||                             T  E  S  T     I  N  P  U  T     -     7  .  2  .  1  0                           ||                             T  E  S  T     I  N  P  U  T     -     7  .  3  .  0  R  C  1                     ||
||                                                                      ||          null |         empty |     last_null |      auto_idx |       shuffle |           100 |        100000 ||          null |         empty |     last_null |      auto_idx |       shuffle |           100 |        100000 ||          null |         empty |     last_null |      auto_idx |       shuffle |           100 |        100000 ||
||============================OPTIONS - ERRORS==========================++===============+===============+===============+===============+===============+===============+===============++===============+===============+===============+===============+===============+===============+===============++===============+===============+===============+===============+===============+===============+===============<|
||  1.  $x = array_values(array_slice($array, -1))[0];                  ||       W1 + W2 |            N1 |             - |             - |             - |             - |             - ||       W1 + W2 |            N1 |             - |             - |             - |             - |             - ||       W1 + W2 |            N1 |             - |             - |             - |             - |             - ||
||  2.  $x = array_slice($array, -1)[0];                                ||            W1 |            N1 |             - |             - |             - |             - |             - ||            W1 |            N1 |             - |             - |             - |             - |             - ||            W1 |            N1 |             - |             - |             - |             - |             - ||
||  3.  $x = array_pop((array_slice($array, -1)));                      ||       W1 + W3 |             - |             - |             - |             - |             - |             - ||  W1 + N2 + W3 |            N2 |            N2 |            N2 |            N2 |            N2 |            N2 ||  W1 + N2 + W3 |            N2 |            N2 |            N2 |            N2 |            N2 |            N2 ||
||  4.  $x = array_pop((array_slice($array, -1, 1)));                   ||       W1 + W3 |             - |             - |             - |             - |             - |             - ||  W1 + N2 + W3 |            N2 |            N2 |            N2 |            N2 |            N2 |            N2 ||  W1 + N2 + W3 |            N2 |            N2 |            N2 |            N2 |            N2 |            N2 ||
||  5.  $x = end($array); reset($array);                                ||       W4 + W5 |             - |             - |             - |             - |             - |             - ||       W4 + W5 |            N2 |            N2 |            N2 |            N2 |            N2 |            N2 ||       W4 + W5 |             - |             - |             - |             - |             - |             - ||
||  6.  $x = end((array_values($array)));                               ||       W2 + W4 |             - |             - |             - |             - |             - |             - ||  W2 + N2 + W4 |             - |             - |             - |             - |             - |             - ||  W2 + N2 + W4 |            N2 |            N2 |            N2 |            N2 |            N2 |            N2 ||
||  7.  $x = $array[count($array)-1];                                   ||             - |            N3 |             - |             - |             - |             - |             - ||            W7 |            N3 |             - |             - |             - |             - |             - ||            W7 |            N3 |             - |             - |             - |             - |             - ||
||  8.  $keys = array_keys($array); $x = $array[$keys[count($keys)-1]]; ||            W6 |       N3 + N4 |             - |             - |             - |             - |             - ||       W6 + W7 |       N3 + N4 |             - |             - |             - |             - |             - ||       W6 + W7 |       N3 + N4 |             - |             - |             - |             - |             - ||
||  9.  $x = $array[] = array_pop($array);                              ||            W3 |             - |             - |             - |             - |             - |             - ||            W3 |             - |             - |             - |             - |             - |             - ||            W3 |             - |             - |             - |             - |             - |             - ||
|| 10.  $x = $array[array_key_last($array)];                            ||            F1 |            F1 |            F1 |            F1 |            F1 |            F1 |            F1 ||            F2 |            F2 |            F2 |            F2 |            F2 |            F2 |            F2 ||            W8 |            N4 |            F2 |            F2 |            F2 |            F2 |            F2 ||
||========================OPTIONS - VALUE RETRIEVED=====================++===============+===============+===============+===============+===============+===============+===============++===============+===============+===============+===============+===============+===============+===============++===============+===============+===============+===============+===============+===============+===============<|
||  1.  $x = array_values(array_slice($array, -1))[0];                  ||          NULL |          NULL |          NULL | string(1) "d" | string(1) "c" |       int(99) |    int(99999) ||          NULL |          NULL |          NULL | string(1) "d" | string(1) "c" |       int(99) |    int(99999) ||          NULL |          NULL |          NULL | string(1) "d" | string(1) "c" |       int(99) |    int(99999) ||
||  2.  $x = array_slice($array, -1)[0];                                ||          NULL |          NULL |          NULL | string(1) "d" | string(1) "c" |       int(99) |    int(99999) ||          NULL |          NULL |          NULL | string(1) "d" | string(1) "c" |       int(99) |    int(99999) ||          NULL |          NULL |          NULL | string(1) "d" | string(1) "c" |       int(99) |    int(99999) ||
||  3.  $x = array_pop((array_slice($array, -1)));                      ||          NULL |          NULL |          NULL | string(1) "d" | string(1) "c" |       int(99) |    int(99999) ||          NULL |          NULL |          NULL | string(1) "d" | string(1) "c" |       int(99) |    int(99999) ||          NULL |          NULL |          NULL | string(1) "d" | string(1) "c" |       int(99) |    int(99999) ||
||  4.  $x = array_pop((array_slice($array, -1, 1)));                   ||          NULL |          NULL |          NULL | string(1) "d" | string(1) "c" |       int(99) |    int(99999) ||          NULL |          NULL |          NULL | string(1) "d" | string(1) "c" |       int(99) |    int(99999) ||          NULL |          NULL |          NULL | string(1) "d" | string(1) "c" |       int(99) |    int(99999) ||
||  5.  $x = end($array); reset($array);                                ||          NULL |   bool(false) |          NULL | string(1) "d" | string(1) "c" |       int(99) |    int(99999) ||          NULL |   bool(false) |          NULL | string(1) "d" | string(1) "c" |       int(99) |    int(99999) ||          NULL |   bool(false) |          NULL | string(1) "d" | string(1) "c" |       int(99) |    int(99999) ||
||  6.  $x = end((array_values($array)));                               ||          NULL |   bool(false) |          NULL | string(1) "d" | string(1) "c" |       int(99) |    int(99999) ||          NULL |   bool(false) |          NULL | string(1) "d" | string(1) "c" |       int(99) |    int(99999) ||          NULL |   bool(false) |          NULL | string(1) "d" | string(1) "c" |       int(99) |    int(99999) ||
||  7.  $x = $array[count($array)-1];                                   ||          NULL |          NULL |          NULL | string(1) "d" | string(1) "b" |       int(99) |    int(99999) ||          NULL |          NULL |          NULL | string(1) "d" | string(1) "b" |       int(99) |    int(99999) ||          NULL |          NULL |          NULL | string(1) "d" | string(1) "b" |       int(99) |    int(99999) ||
||  8.  $keys = array_keys($array); $x = $array[$keys[count($keys)-1]]; ||          NULL |          NULL |          NULL | string(1) "d" | string(1) "c" |       int(99) |    int(99999) ||          NULL |          NULL |          NULL | string(1) "d" | string(1) "c" |       int(99) |    int(99999) ||          NULL |          NULL |          NULL | string(1) "d" | string(1) "c" |       int(99) |    int(99999) ||
||  9.  $x = $array[] = array_pop($array);                              ||          NULL |          NULL |          NULL | string(1) "d" | string(1) "c" |       int(99) |    int(99999) ||          NULL |          NULL |          NULL | string(1) "d" | string(1) "c" |       int(99) |    int(99999) ||          NULL |          NULL |          NULL | string(1) "d" | string(1) "c" |       int(99) |    int(99999) ||
|| 10.  $x = $array[array_key_last($array)];                            ||           N/A |           N/A |           N/A |           N/A |           N/A |           N/A |           N/A ||           N/A |           N/A |           N/A |           N/A |           N/A |           N/A |           N/A ||           N/A |           N/A |           N/A |           N/A |           N/A |           N/A |           N/A ||
||=================OPTIONS - FEMTOSECONDS PER ITERATION=================++===============+===============+===============+===============+===============+===============+===============++===============+===============+===============+===============+===============+===============+===============++===============+===============+===============+===============+===============+===============+===============<|
||  1.  $x = array_values(array_slice($array, -1))[0];                  ||           803 |           466 |           390 |           384 |           373 |           764 |     1.046.642 ||           691 |           252 |           101 |           128 |            93 |           170 |        89.028 ||           695 |           235 |            90 |            97 |            95 |           188 |        87.991 ||
||  2.  $x = array_slice($array, -1)[0];                                ||           414 |           349 |           252 |           248 |           246 |           604 |     1.038.074 ||           373 |           249 |            85 |            91 |            90 |           164 |        90.750 ||           367 |           224 |            78 |            85 |            80 |           155 |        86.141 ||
||  3.  $x = array_pop((array_slice($array, -1)));                      ||           724 |           228 |           323 |           318 |           350 |           673 |     1.042.263 ||           988 |           285 |           309 |           317 |           331 |           401 |        88.363 ||           877 |           266 |           298 |           300 |           326 |           403 |        87.279 ||
||  4.  $x = array_pop((array_slice($array, -1, 1)));                   ||           734 |           266 |           358 |           356 |           349 |           699 |     1.050.101 ||           887 |           288 |           316 |           322 |           314 |           408 |        88.402 ||           935 |           268 |           335 |           315 |           313 |           403 |        86.445 ||
||  5.  $x = end($array); reset($array);                                ||           715 |           186 |           185 |           180 |           176 |           185 |           172 ||           674 |            73 |            69 |            70 |            66 |            65 |            70 ||           693 |            65 |            85 |            74 |            68 |            70 |            69 ||
||  6.  $x = end((array_values($array)));                               ||           877 |           205 |           320 |           337 |           304 |         2.901 |     7.921.860 ||           948 |           300 |           336 |           308 |           309 |           509 |    29.696.951 ||           946 |           262 |           301 |           309 |           302 |           499 |    29.234.928 ||
||  7.  $x = $array[count($array)-1];                                   ||           123 |           300 |           137 |           139 |           143 |           140 |           144 ||           312 |           218 |            48 |            53 |            45 |            47 |            51 ||           296 |           217 |            46 |            44 |            53 |            53 |            55 ||
||  8.  $keys = array_keys($array); $x = $array[$keys[count($keys)-1]]; ||           494 |           593 |           418 |           435 |           399 |         3.873 |    12.199.450 ||           665 |           407 |           103 |           109 |           114 |           431 |    30.053.730 ||           647 |           445 |            91 |            95 |            96 |           419 |    30.718.586 ||
||  9.  $x = $array[] = array_pop($array);                              ||           186 |           178 |           175 |           188 |           180 |           181 |           186 ||            83 |            78 |            75 |            71 |            74 |            69 |            83 ||            71 |            64 |            70 |            64 |            68 |            69 |            81 ||
|| 10.  $x = $array[array_key_last($array)];                            ||           N/A |           N/A |           N/A |           N/A |           N/A |           N/A |           N/A ||           N/A |           N/A |           N/A |           N/A |           N/A |           N/A |           N/A ||           370 |           223 |            49 |            52 |            61 |            57 |            52 ||
 =========================================================================================================================================================================================================================================================================================================================================================================================================================/ 

The above mentioned Fatal, Warning and Notice codes translate as:

F1 = Fatal error: Call to undefined function array_key_last() in Command line code on line 1
F2 = Fatal error: Uncaught Error: Call to undefined function array_key_last() in Command line code:1
W1 = Warning: array_slice() expects parameter 1 to be array, null given in Command line code on line 1
W2 = Warning: array_values() expects parameter 1 to be array, null given in Command line code on line 1
W3 = Warning: array_pop() expects parameter 1 to be array, null given in Command line code on line 1
W4 = Warning: end() expects parameter 1 to be array, null given in Command line code on line 1
W5 = Warning: reset() expects parameter 1 to be array, null given in Command line code on line 1
W6 = Warning: array_keys() expects parameter 1 to be array, null given in Command line code on line 1
W7 = Warning: count(): Parameter must be an array or an object that implements Countable in Command line code on line 1
W8 = Warning: array_key_last() expects parameter 1 to be array, null given in Command line code on line 1
N1 = Notice: Undefined offset: 0 in Command line code on line 1
N2 = Notice: Only variables should be passed by reference in Command line code on line 1
N3 = Notice: Undefined offset: -1 in Command line code on line 1
N4 = Notice: Undefined index:  in Command line code on line 1

Based on this output I draw the following conclusions:

  • newer versions of PHP perform better with the exception of these options that became significantly slower:
    • option .6. $x = end((array_values($array)));
    • option .8. $keys = array_keys($array); $x = $array[$keys[count($keys)-1]];
  • these options scale best for very large arrays:
    • option .5. $x = end($array); reset($array);
    • option .7. $x = $array[count($array)-1];
    • option .9. $x = $array[] = array_pop($array);
    • option 10. $x = $array[array_key_last($array)]; (since PHP 7.3)
  • these options should only be used for auto-indexed arrays:
    • option .7. $x = $array[count($array)-1]; (due to use of count)
    • option .9. $x = $array[] = array_pop($array); (due to assigning value losing original key)
  • this option does not preserve the array’s internal pointer
    • option .5. $x = end($array); reset($array);
  • this option is an attempt to modify option .5. to preserve the array’s internal pointer (but sadly it does not scale well for very large arrays)
    • option .6. $x = end((array_values($array)));
  • the new array_key_last function seems to have none of the above mentioned limitations with the exception of still being an RC at the time of this writing (so use the RC or await it’s release Dec 2018):
    • option 10. $x = $array[array_key_last($array)]; (since PHP 7.3)

A bit depending on whether using the array as stack or as queue you can make variations on option 9.

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

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

Описание

end(array|object &$array): mixed

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

array

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

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

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

Список изменений

Версия Описание
8.1.0 Вызов функции в объекте (object) объявлен устаревшим.
Либо сначала преобразуйте объект (object) в массив (array) с помощью функции get_mangled_object_vars(),
либо используйте методы, предоставляемые классом, реализующим интерфейс Iterator,
например, ArrayIterator.
7.4.0 Экземпляры классов SPL теперь обрабатываются как пустые объекты,
не имеющие свойств, вместо вызова метода Iterator с тем же именем, что и эта функция.

Примеры

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


<?php

$fruits

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

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

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

franz at develophp dot org

12 years ago


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".


jasper at jtey dot com

16 years ago


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"
?>


jorge at REMOVETHIS-2upmedia dot com

11 years ago


If all you want is the last item of the array without affecting the internal array pointer just do the following:

<?phpfunction 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.


Anonymous

20 years ago


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

}

?>


ivijan dot stefan at gmail dot com

9 years ago


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.


Jason

10 years ago


$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);


ken at expitrans dot com

17 years ago


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:

<?phpecho ">> ".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";?>


Aleksandr

5 years ago


<?php
$A
=[1];
print_r($A);
end($A[5]);
print_r($A);
?>

Array
(
    [0] => 1
)
Array
(
    [0] => 1
    [5] =>
)

laurence at crazypillstudios dot com

12 years ago


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.


Jacob

5 years ago


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


Anonymous

20 years ago


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);

}

?>


Sam Yong – hellclanner at live dot com

13 years ago


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.


Omolewa stephen

6 years ago


I found using pathinfo very useful in getting extension of  a file.
<? Php
  $filename = dictionary.txt;
   $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION)) ;

echo $ext; // txt
?>


aaaaa976 at gmail dot com

4 years ago


To get the first element:

    // Get first item.
    foreach ($array as $item) {
        $first = $item;
        break;
    }
    // $first will have the first element.


goran

7 years ago


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 ', ';
            }
        }


I am trying to find the last element in the array by using foreach loop.

I have..

  foreach ( $employees as $employee ) {

         $html.=$employee ->name.'and ';

  }

I don’t want to add ‘and’ to the last employee. Are there anyways to do this? Thanks a lot!

asked Oct 16, 2012 at 23:22

FlyingCat's user avatar

There’s another way, I suppose:

$html = implode(' and ', 
  array_map(function($el) { return $el->name; }, $employees));

It’s simple: array_map will create an array of $employee->name elements, and implode will make a string from these, using ' and ' string as ‘glue’. )

answered Oct 16, 2012 at 23:24

raina77ow's user avatar

raina77owraina77ow

103k14 gold badges191 silver badges229 bronze badges

0

A cleaner approach than having a counter in your foreach could be to simply remove the final “and ” off of your string.

foreach ($employees as $employee) {
    $html .= $employee->name . 'and ';
}
$html = substr($html, 0, strlen($html) - 4);

answered Oct 16, 2012 at 23:26

FThompson's user avatar

FThompsonFThompson

28.3k12 gold badges59 silver badges92 bronze badges

Один вариант уже был (для сравнения его тоже приведу), теперь ещё один:

foreach ($array as $key => $value) {
  if($value == end($array)) {
        // делаем что-либо с последним элементом...
  }
  else {
        // делаем что-либо с каждым элементом
  }
}

Вариант Kost

foreach ($array as $key => $value) {
   if (!next($array)) {
        // делаем что-либо с последним элементом...
   }
   else {
       // делаем что-либо с каждым элементом
   }
}

edit1:

Спасибо dkrnl. Устроил тест.

Вариант №1 работает только если явно задать ключи:

$array = array('1' => '1','2' => '2','3' => '3', '4'=>'4','5'=>'5');

Вариант №2 работает только если массив передать по ссылке:

$array = new ArrayObject(array(1,2,3,4,5));

Работающий в любом случае вариант:

$total = count($array);
$counter = 0;
foreach($array as $key => value){
  $counter++;
  if($counter == $total){
    // делаем что-либо с последним элементом...
  }
  else{
    // делаем что-либо с каждым элементом
  }
}

edit2:

А ведь и правда стало смахивать на for 🙂 Неудобство в том, что при обращении к элементу в случае с for придётся использовать индекс.

edit3:

Неплохое решение DeadLy:

$end_element = array_pop($array);
foreach ($array as $value) {
   // делаем что-либо с каждым элементом
}
   // делаем что-либо с последним элементом $end_element

Смотря что подразумевается под словом “получить”. Если нужно именно извлечь (получить элемент и уменьшить длину массива) последний элемент массива, то можно воспользоваться функцией array_pop():

<?php

$numbers = [1, 2, 3, 4];
$lastNumber = array_pop($numbers);
print_r($numbers); //=> [1, 2, 3]
// Исходный массив уменьшился на один элемент

А если изменять исходный массив нельзя, то можно воспользоваться функцией array_key_last(). Эта функция получает ключ последнего элемента массива, а потом можно получить и сам последний элемент. Взгляните на пример:

<?php

$numbers = [1, 2, 3, 4];
$lastNumber = $numbers[array_key_last($numbers)];
print_r($numbers); //=> [1, 2, 3, 4]
// Исходный массив при этом не изменился

Добавить комментарий