>  기사  >  백엔드 개발  >  PHP의 새로운 배열 함수

PHP의 새로운 배열 함수

王林
王林원래의
2024-08-19 18:43:331046검색

New Array Functions in PHP

소개

PHP 8.4는 2024년 11월에 출시될 예정이며 몇 가지 편리한 새 배열 기능을 도입할 예정입니다.

  • 배열_찾기
  • array_find_key
  • array_any
  • array_all

이 기사에서는 이러한 새로운 기능을 간략히 살펴보고 PHP 8.4를 실행하는 프로젝트에서 해당 기능을 사용하는 방법을 살펴보겠습니다.

Laravel 개발자라면 IlluminateSupportCollection 및 IlluminateSupportArr 클래스에 이미 유사한 기능이 있다는 것을 알 수 있을 것입니다. 하지만 저는 이러한 기능이 PHP에 기본적으로 포함되어 모든 PHP 프로젝트에서 사용할 수 있다는 점을 좋아합니다.

Laravel 개발자인 독자들을 위해 PHP 8.4를 기다리지 않고도 Laravel 프로젝트에서 동일한 기능을 얻을 수 있도록 이러한 새로운 기능에 해당하는 Laravel 기능을 보여 드리겠습니다.

PHP 8.4의 새로운 "속성 후크" 기능에 대해 설명하는 다른 기사도 확인해 보세요.

array_find 함수

array_find 함수는 콜백에 정의된 기준과 일치하는 첫 번째 요소의 값을 반환합니다. 콜백과 일치하는 요소가 없으면 함수는 null을 반환합니다.

간단한 예를 살펴보겠습니다. 우리는 일련의 제품이 있고 바코드가 123456인 제품을 찾고 싶다고 가정합니다.

$products = [
    [
        'name' => 'Macbook Pro',
        'type' => 'Laptop',
        'barcode' => 123456,
    ],
    [
        'name' => 'Framework Laptop 13',
        'type' => 'Laptop',
        'barcode' => 789012,
    ],
    [
        'name' => 'Samsung Galaxy S24',
        'type' => 'Phone',
        'barcode' => 135791,
    ],
];

// Find the product with barcode 123456
$findProduct = array_find(
    array: $products,
    callback: function (array $product): bool {
        return $product['barcode'] == 123456;
    },
);

위 코드를 실행하면 $findProduct는 다음과 같습니다.

[
    'name'=> 'Macbook Pro',
    'type' => 'Laptop',
    'barcode' => 123456,
]

화살표 함수를 두 번째 인수로 사용하여 이를 좀 더 정리할 수 있습니다.

$findProduct = array_find(
    array: $products,
    callback: fn (array $product): bool => $product['barcode'] === 123456,
);

위 코드는 이전 예제와 동일한 결과를 반환합니다.

콜백과 일치하는 요소가 없으면 함수는 null을 반환합니다. 이에 대한 예를 살펴보겠습니다.

$nonExistentProduct = array_find(
    array: $products,
    callback: fn (array $product): bool => $product['barcode'] === 'invalid',
);

이 경우 $nonExistentProduct는 null과 같습니다.

라라벨 등가물

Laravel에서는 Arr::first 메소드를 사용하여 비슷한 결과를 얻을 수 있습니다.

use Illuminate\Support\Arr;

$findProduct = Arr::first(
    $products,
    fn (array $product): bool => $product['barcode'] === 123456,
);

array_find_key 함수

이 함수는 array_find 함수와 유사하지만 콜백과 일치하는 첫 번째 요소의 값을 반환하는 대신 콜백과 일치하는 첫 번째 요소의 키를 반환합니다.

이전의 $products 예제 배열을 살펴보겠습니다. 이번에는 바코드가 789012인 제품의 키를 찾아보겠습니다:

$products = [
    [
        'name' => 'Macbook Pro',
        'type' => 'Laptop',
        'barcode' => 123456,
    ],
    [
        'name' => 'Framework Laptop 13',
        'type' => 'Laptop',
        'barcode' => 789012,
    ],
    [
        'name' => 'Samsung Galaxy S24',
        'type' => 'Phone',
        'barcode' => 135791,
    ],
];

// Find the key of the product with barcode 789012
$findProduct = array_find_key(
    array: $products,
    callback: fn (array $product): bool => $product['barcode'] === 789012,
);

위 코드를 실행하면 제품이 배열의 두 번째 요소이므로 $findProduct는 1이 됩니다.

콜백과 일치하는 요소가 없으면 함수는 null을 반환합니다. 이에 대한 예를 살펴보겠습니다.

$nonExistentProduct = array_find_key(
    array: $products,
    callback: fn (array $product): bool => $product['barcode'] === 'invalid',
);

이 경우 $nonExistentProduct는 null과 같습니다.

라라벨 등가물

Laravel에서는 array_keys와 Arr::first 메소드의 조합을 사용하여 비슷한 결과를 얻을 수 있습니다.

use Illuminate\Support\Arr;

$firstProductKey = Arr::first(
    array_keys($products),
    fn (int $key): bool => $products[$key]['barcode'] === 789012,
);

위 코드에서는 먼저 array_keys를 사용하여 $products 배열의 키 배열을 가져옵니다. 그런 다음 Arr::first를 사용하여 콜백과 일치하는 첫 번째 키를 찾습니다. 이는 기본 PHP 함수보다 조금 더 장황하지만 동일한 결과를 얻습니다.

array_any 함수

array_any 함수를 사용하면 배열에 있는 하나 이상의 요소가 콜백에 정의된 기준과 일치하는지 확인할 수 있습니다. 콜백과 일치하는 요소가 있으면 함수는 true를 반환합니다. 콜백과 일치하는 요소가 없으면 함수는 false를 반환합니다.

$products 예제 배열을 사용하여 노트북 유형이 있는 제품이 있는지 확인해 보겠습니다.

$anyProductsAreLaptops = array_any(
    array: $products,
    callback: fn (array $product): bool => $product['type'] === 'Laptop',
);

이 경우 배열의 제품 중 하나 이상이 노트북이기 때문에 $anyProductsAreLaptops는 true와 같습니다.

콜백과 일치하는 요소가 없으면 함수는 false를 반환합니다. 이에 대한 예를 살펴보겠습니다.

$anyProductsAreInvalid = array_any(
    array: $products,
    callback: fn (array $product): bool => $product['type'] === 'Invalid',
);

이 경우 $anyProductsAreInvalid는 false와 같습니다.

라라벨 등가물

컬렉션에 포함 메소드를 사용하면 Laravel에서 동일한 결과를 얻을 수 있습니다.

use Illuminate\Support\Collection;

$anyProductsAreLaptops = Collection::make($products)->contains(
    fn (array $product): bool => $product['type'] === 'Laptop',
);

위 코드에서는 $products 배열에서 컬렉션을 생성한 다음 포함 메소드를 사용하여 컬렉션에 노트북 제품이 있는지 확인합니다.

array_all 함수

array_all 함수는 array_any 함수와 유사하지만 하나 이상의 요소가 콜백과 일치하는지 확인하는 대신 모든 요소가 콜백과 일치하는지 확인합니다. 모든 요소가 콜백과 일치하면 함수는 true를 반환합니다. 콜백과 일치하지 않는 요소가 있으면 함수는 false를 반환합니다.

$products 배열의 모든 제품이 노트북인지 확인해 보겠습니다.

$allProductsAreLaptops = array_all(
    array: $products,
    callback: fn (array $product): bool => $product['type'] === 'Laptop',
);

이 경우 배열의 모든 제품이 노트북이 아니기 때문에 $allProductsAreLaptops는 false와 같습니다.

Laravel Equivalent

In Laravel, we can achieve the same result using the every method on a collection:

use Illuminate\Support\Collection;

$allProductsAreLaptops = Collection::make($products)->every(
    fn (array $product): bool => $product['type'] === 'Laptop',
);

In the code above, we're creating a collection from the $products array and then using the every method to check if all the products in the collection are laptops.

Conclusion

Hopefully, this article has shown you how you can use the new array functions that will be available in PHP 8.4. It should have also given you an idea of how you can achieve similar functionality in Laravel using the Illuminate\Support\Collection and Illuminate\Support\Arr classes.

If you enjoyed reading this post, you might be interested in checking out my 220+ page ebook "Battle Ready Laravel" which covers similar topics in more depth.

Or, you might want to check out my other 440+ page ebook "Consuming APIs in Laravel" which teaches you how to use Laravel to consume APIs from other services.

If you're interested in getting updated each time I publish a new post, feel free to sign up for my newsletter.

Keep on building awesome stuff! ?

위 내용은 PHP의 새로운 배열 함수의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.