Witaj Gościu! ( Zaloguj | Rejestruj )

Forum PHP.pl

> Pobieranie ostatniego elementu tablicy, (bez kasowania go)
Asmox
post 7.06.2012, 20:35:38
Post #1





Grupa: Zarejestrowani
Postów: 359
Pomógł: 12
Dołączył: 16.01.2009

Ostrzeżenie: (0%)
-----


Szukam funkcji, która pobrałaby ostatni element tablicy bez usuwania go, tak jak to robi array_pop. Niestety nie znalazłem jej, a w komentarzach do array_pop znalazłem tylko funkcję podobną, którą mógłbym przerobić na własny użytek:
Cytat
sneskid at hotmail dot com 03-Aug-2009 07:22
As already mentioned, array_pop always returns a copy, never a reference, which can be a problem in some cases.
Here is a pop function that allows you to get the reference.
(keep in mind it will alter the internal pointer of the array)

  1. function &array_rpop(&$a){
  2. end($a);
  3. $k=key($a);
  4. $v=&$a[$k];
  5. unset($a[$k]);
  6. return $v;
  7. }
  8.  
  9. // try this:
  10. $A='A';
  11. $B=array(&$A);
  12.  
  13. //$C=&array_rpop($B); // will work
  14. $C=&array_pop($B); // won't work
  15.  
  16. $C='C';
  17.  
  18. var_dump($A,$B,$C);

Cytat
I hope the PHP people will make the regular function work with references.

Pomyślałem żeby zrobić u siebie implementację takiej funkcji ale nie wiem, czy jest to najbardziej wydajne rozwiązanie? Czy może bardziej opłaca się zrobić coś w stylu poniższego kodu?
  1. $originalArr = array('raz', 'dwa', 'trzy');
  2. $copiedArr = $originalArr;
  3. $lastElement = array_pop($copiedArr);


--------------------
Go to the top of the page
+Quote Post

Posty w temacie


Reply to this topicStart new topic
1 Użytkowników czyta ten temat (1 Gości i 0 Anonimowych użytkowników)
0 Zarejestrowanych:

 



RSS Wersja Lo-Fi Aktualny czas: 13.08.2025 - 23:20