PHP Stories: Letztes Array Element original

by Toby Maxham – 1 minute read

Heute zeige ich euch, wie man mit einem kleinen Trick das letzte Element eines Arrays herausfindet. Dabei finde ich diese Vorgehensweise besser gelöst als mit einem count().

Hier nun das Beispiel:

<?php // lastArrayExample.php
$array = array('Toby', 'John', 'Leo', 'John');

// Pointer an das Ende des Arrays setzten
end($array);

// Den Key des Elements holen
$lastKey = key($array);

foreach($array as $k => $v) {
    if($k == $lastKey) {
         echo $v . ' ist der letzte!';
    } else
	echo $v . '<br />';
}
// Ausgabe: Toby<br />John<br />Leo<br />John ist der letzte!

Join the newsletter

Occasional thoughts on Laravel, PHP, and building real-world applications — straight from what I’m working on.

The newsletter is on a little break right now — see you soon!

Found something interesting to share? Submit a link to the community section.