How to declare an array of specific type in php?

Member

by darion , in category: PHP General , 5 months ago

How to declare an array of specific type in php?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by gilbert , 5 months ago

@darion 

To declare an array of a specific type in PHP, you can use type hints in the function signature or class property declaration.


For example, to declare an array of integers, you can use the type hint int[]:

1
2
3
4
5
6
function myFunction(array $numbers) {
  // ...
}

myFunction([1, 2, 3]); // valid
myFunction(['1', '2', '3']); // throws a type error


Similarly, you can use type hints for arrays in class properties:

1
2
3
4
5
6
7
class MyClass {
  public array $myArray;
}

$instance = new MyClass();
$instance->myArray = [1, 2, 3]; // valid
$instance->myArray = ['1', '2', '3']; // throws a type error


It's important to note that PHP is a dynamically typed language, so these type hints are not enforced at runtime. They serve as hints for developers and can be used for static code analysis.