php bir dizinin 1 değerini almak (birleştirici ya da değil)

2 Cevap php

Bu kudreti saçma bir soru gibi geliyor. Nasıl dizi çağrışımlı olup olmadığını önceden bilmeden bir dizinin 1 değerini alabilirim?

Bunu yapmak için düşünülen bir dizinin 1. elemanını almak için:

function Get1stArrayValue($arr) { return current($arr); }

is it ok? Could it create issues if array internal pointer was moved before function call? Is there a better/smarter/fatser way to do it?

Teşekkürler!

2 Cevap

Daha iyi bir fikir "ilk elemanı dizinin dahili göstericisi sarar ve ilk dizi öğesinin değerini verir" reset hangi kullanmak olabilir

Örnek:

function Get1stArrayValue($arr) { return reset($arr); }

As @therefromhere pointed out in the comment below, this solution is not ideal as it changes the state of the internal pointer. However, I don't think it is much of an issue as other functions such as array_pop also reset it.
The main concern that it couldn't be used when iterating over an array isn't an problem as foreach operates on a copy of the array. The PHP manual states:

Dizi başvurulan sürece, foreach dizi değil dizinin kendisi bir kopyası üzerinde çalışır.

Bu bazı basit test kodu kullanılarak gösterilebilir:

$arr = array("a", "b", "c", "d");
foreach ( $arr as $val ){
    echo reset($arr) . " - " . $val . "\n";
}

Sonuç:

a - a
a - b
a - c
a - d

Eğer dizinin ilk elemanı kaybetme sakıncası yoksa, siz de kullanabilirsiniz

array_shift() - shifts the first value of the array off and returns it, shortening the array by one element and moving everything down. All numerical array keys will be modified to start counting from zero while literal keys won't be touched.

Yoksa bir ArrayIterator içine dizi sarın ve kullanmak seek :

$array = array("foo" => "apple", "banana", "cherry", "damson", "elderberry");
$iterator = new ArrayIterator($array);
$iterator->seek(0);
echo $iterator->current(); // apple

Bu da bir seçenek değildir, diğer öneri birini kullanabilirsiniz.