Is PHP-specific string array possible?

Asked

Viewed 34 times

0

Well, I have the code below that should work but gives error:

function teste( string... $_array ) : array {

    //FINS DE TESTE

    return $_array;

}

print_r (   teste ( ["teste","2"] ) );

If I just do

 function teste( array $_array ) : array {

        //FINS DE TESTE

        return $_array;

    }

works!

But I’d like to specify that the array is of strings only.

How to do this in PHP?

1 answer

2


Until PHP 7 there was no way to specify the type of array, I also wish I could. However, I don’t know if in recent versions such a resource has been added.

But, your first code works, just by adding the ... in the array:

// Inalterado
function teste( string... $_array ) : array {
    return $_array;
}

// Acrescentado o `...` antes da array
print_r(teste( ...["teste","2"]));

The ...["teste","2"] will make each item a value.

  • I really wanted it to specify the type. Mainly to be able to do something like: function() : array[array, bool] {}, thus specifying that the function returns an array where the first is another array and the second the boolean value, which would be an error sign.

  • Parse error: syntax error, Unexpected ':', expecting '{' in /var/www/html/gasmuriae.com.br/web/gceu/teste.php on line 7

  • line 7 is: Function test( string... $_array ) array {

  • @Carlosrocha, this works normally at http://sandbox.onlinephpfunctions.com/code/8f099274ab7cbded7c4348e8f963bff5d9521b1b (PHP 7.2).

  • thanks. let’s hope they improve this because ...["test","2"] is a shame for PHP 7.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.