Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a php function with predefined values for a parameter

Tags:

php

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?

like image 723
Alex Avatar asked Apr 13 '16 09:04

Alex


2 Answers

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"
    }
}
like image 79
Sashant Pardeshi Avatar answered Oct 06 '22 00:10

Sashant Pardeshi


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;
}
like image 27
Pupil Avatar answered Oct 06 '22 00:10

Pupil