Programing

연관 PHP 배열에서 첫 번째 항목을 얻는 방법은 무엇입니까?

lottogame 2020. 6. 28. 18:27
반응형

연관 PHP 배열에서 첫 번째 항목을 얻는 방법은 무엇입니까?


내가 같은 배열을 가지고 있다면 :

$array['foo'] = 400;
$array['bar'] = 'xyz';

그리고 키를 모른 채 배열에서 첫 번째 항목을 가져오고 싶습니다. 어떻게해야합니까? 이것에 대한 기능이 있습니까?


reset() 배열 안에 요소가있는 경우 배열의 첫 번째 값을 제공합니다.

$value = reset($array);

FALSE배열이 비어있는 경우 에도 제공합니다 .


첫 번째 반복에서 중단되는 가짜 루프 :

$key = $value = NULL;
foreach ($array as $key => $value) {
    break;
}

echo "$key = $value\n";

또는 each()( 경고 : PHP 7.2.0부터 더 이상 사용되지 않음 ) :

reset($array);
list($key, $value) = each($array);

echo "$key = $value\n";

PHP <7.3

배열에 대해 충분히 알지 못하면 (첫 번째 키가 foo 인지 bar 인지 확실하지 않은 경우) 배열도 비어 있을 수 있습니다 .

따라서 반환 된 값이 부울 FALSE 일 가능성이있는 경우 특히 확인하는 것이 가장 좋습니다.

$value = empty($arr) ? $default : reset($arr);

위의 코드의 사용 reset등은 부작용을 가지고 사용을 선호 할 수 있도록 (이 배열의 내부 포인터를 재설정) array_slice신속하게 배열의 첫 번째 요소의 사본을 액세스 할 수 :

$value = $default;
foreach(array_slice($arr, 0, 1) as $value);

키와 값을 별도로 가져 오려면 다음에 네 번째 매개 변수를 추가해야합니다 array_slice.

foreach(array_slice($arr, 0, 1, true) as $key => $value);

첫 번째 항목 을 한 쌍으로 가져 오려면 ( key => value) :

$item = array_slice($arr, 0, 1, true);

마지막 항목, 키 및 값을 별도로 가져 오는 간단한 수정 :

foreach(array_slice($arr, -1, 1, true) as $key => $value);

공연

배열이 실제로 크지 않은 경우 실제로 array_slice전체 키 배열의 사본이 필요하지 않고 오히려 첫 번째 항목을 얻을 수 있습니다.

$key = count($arr) ? array_keys($arr)[0] : null;

그러나 배열이 매우 큰 경우 호출에 array_keys많은 시간과 메모리가 필요합니다 array_slice(두 함수 모두 배열을 걷지 만 필요한 수의 항목을 수집하자마자 종료됩니다).

주목할만한 예외는 매우 크고 복잡한 객체를 가리키는 첫 번째 키가있는 경우입니다. 이 경우 array_slice첫 번째 큰 객체를 복제 array_keys하고 키만 가져옵니다.

PHP 7.3

PHP 7.3 array_key_first()뿐만 아니라 구현 array_key_last()합니다. 이는 어레이의 내부 상태를 부작용으로 재설정하지 않고 첫 번째 키와 마지막 키에 효율적으로 액세스 할 수 있도록 명시 적으로 제공됩니다.

그래서 PHP 7.3의 첫 번째 의은 $array에 액세스 할 수 있습니다

$array[array_key_first($array)];

그래도 배열이 비어 있지 않은지 확인하는 것이 좋습니다. 그렇지 않으면 오류가 발생합니다.

$firstKey = array_key_first($array);
if (null === $firstKey) {
    $value = "Array is empty"; // An error should be handled here
} else {
    $value = $array[$firstKey];
}

몇 가지 옵션이 있습니다. array_shift()첫 번째 요소를 반환하지만 배열에서 첫 번째 요소도 제거합니다.

$first = array_shift($array);

current() 내부 메모리 포인터가 가리키는 배열의 값을 반환합니다. 이것은 기본적으로 첫 번째 요소입니다.

$first = current($array);

첫 번째 요소를 가리키는 지 확인하려면 항상을 사용할 수 있습니다 reset().

reset($array);
$first = current($array);

그냥 그래서 우리는 몇 가지 다른 옵션을 가지고 : reset($arr);당신이 매우 큰 배열을하고, 장소에 배열 포인터를 유지하려고하지 않는 경우 충분한 그것을 오버 헤드의 최소 금액을 초래한다. 그러나 몇 가지 문제가 있습니다.

$arr = array(1,2);
current($arr); // 1
next($arr);    // 2
current($arr); // 2
reset($arr);   // 1
current($arr); // 1 !This was 2 before! We've changed the array's pointer.

포인터를 변경하지 않고이 작업을 수행하는 방법 :

$arr[reset(array_keys($arr))]; // OR
reset(array_values($arr));

$arr[reset(array_keys($arr))];배열이 실제로 비어 있으면 경고가 발생한다는 이점이 있습니다.


another easy and simple way to do it use array_values

array_values($array)[0]

Test if the a variable is an array before getting the first element. When dynamically creating the array if it is set to null you get an error.

For Example:

if(is_array($array))
{
  reset($array);
  $first = key($array);
}

We can do $first = reset($array);

Instead of

reset($array);
$first = current($array);

As reset()

returns the first element of the array after reset;


Use reset() function to get the first item out of that array without knowing the key for it like this.

$value = array('foo' => 400, 'bar' => 'xyz');
echo reset($value);

output // 400


You can try this.

To get first value of the array :-

<?php
   $large_array = array('foo' => 'bar', 'hello' => 'world');
   var_dump(current($large_array));
?>

To get the first key of the array

<?php
   $large_array = array('foo' => 'bar', 'hello' => 'world');
   $large_array_keys = array_keys($large_array);
   var_dump(array_shift($large_array_keys));
?>

You could use array_shift


I do this to get the first and last value. This works with more values too.

$a = array(
    'foo' => 400,
    'bar' => 'xyz',
);
$first = current($a);   //400
$last = end($a);    //xyz

You can make:

$values = array_values($array);
echo $values[0];

Starting with PHP 7.3.0 it's possible to do without resetting the internal pointer. You would use array_key_first. If you're sure that your array has values it in then you can just do:

$first = $array[array_key_first($array)];

More likely, you'll want to handle the case where the array is empty:

$first = (empty($array)) ? $default : $array[array_key_first($array)];

you can just use $array[0]. it will give you the first item always

참고URL : https://stackoverflow.com/questions/1617157/how-to-get-the-first-item-from-an-associative-php-array

반응형