Let's say I have the following method:
public function chooseCar($car)
{
return 'You chose this car: ' . $car;
}
I need to set specific values for what can be passed to chooseCar in the $car argument, for example let the developer choose between 'Mercedes', 'BMW' and 'Ford', is that doable in php?
You may try below code.
public function chooseCar($car)
{
$predefined_vals = array( 'Mercedes', 'BMW', 'Ford');
if(in_array($car,$predefined_vals)){
return 'You chose this car: ' . $car;
}else{
return "undefined values chosen"
}
}
I have one approach for this.
In the function itself, create an array.
And check if the parameter $car
is in_array()
public function chooseCar($car = '') {
$allowedCars = array('Mercedes', 'BMW', 'Ford');
if (! in_array($car, $allowedCars)) {
return FALSE;
}
return 'You chose this car: ' . $car;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With