Laravel collections

méthode nth()

Quand est apparue cette méthode ?

depuis Laravel v5.4

Description


Exemples

Il y a 2 exemples pour cette collection

Exemple #1 : Récupérer 1 élément sur 3

Collection utilisée

    
        // define languages collection
        $this->languages = collect([
            'php',
            'python',
            'javascript',
            'go',
            'c#',
            'java',
            'cobol',
            'basic'
        ]);

        Illuminate\Support\Collection {#413 ▼
            #items: array:8 [▼
                0 => "php"
                1 => "python"
                2 => "javascript"
                3 => "go"
                4 => "c#"
                5 => "java"
                6 => "cobol"
                7 => "basic"
            ]
        }
    

Code source


$languages = collect([
            "php",
            "python",
            "javascript",
            "go",
            "c#",
            "java",
            "cobol",
            "basic"
            ]);

print_r($languages->nth(3));

Résultat

    
Illuminate\Support\Collection Object
(
    [items:protected] => Array
        (
            [0] => php
            [1] => go
            [2] => cobol
        )

)
    

Exemple #2 : Récupérer 1 élément sur 3 avec un offset

Collection utilisée

    
        // define languages collection
        $this->languages = collect([
            'php',
            'python',
            'javascript',
            'go',
            'c#',
            'java',
            'cobol',
            'basic'
        ]);

        Illuminate\Support\Collection {#413 ▼
            #items: array:8 [▼
                0 => "php"
                1 => "python"
                2 => "javascript"
                3 => "go"
                4 => "c#"
                5 => "java"
                6 => "cobol"
                7 => "basic"
            ]
        }
    

Code source


$languages = collect([
            "php",
            "python",
            "javascript",
            "go",
            "c#",
            "java",
            "cobol",
            "basic"
            ]);

print_r($languages->nth(3, 1));

Résultat

    
Illuminate\Support\Collection Object
(
    [items:protected] => Array
        (
            [0] => python
            [1] => c#
            [2] => basic
        )

)