Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function doSomething($actionStr, ...$args){
- $actionArr = str_split($actionStr);
- foreach($args as $i => $n) {
- switch ($actionArr[$i]) {
- case 'd':
- echo "Decimal: " . $n . '<br>';
- break;
- case 's':
- echo "String: " . $n . '<br>';
- break;
- default:
- break;
- }
- }
- }
- // ------------- CASE 1 ---------------------------
- // In this case I have 5 arguments. So I can do this:
- $a = 10;
- $b = 20;
- $c = 'hello';
- $d = 'cheese';
- $e = 500;
- if($a && $b && $c && $d && $e){
- doSomething('ddssd', $a, $b, $c, $d, $e);
- }
- /* OUTPUT:
- Decimal: 10
- Decimal: 20
- String: hello
- String: cheese
- Decimal: 500
- */
- echo '<hr>';
- // ------------- CASE 2 ---------------------------
- // I'm using 4 variables
- $e = null;
- if($a && $b && $c && $d && !$e){
- doSomething('ddss', $a, $b, $c, $d);
- }
- /* OUTPUT:
- Decimal: 10
- Decimal: 20
- String: hello
- String: cheese
- */
- echo '<hr>';
- // ------------- CASE 3 ---------------------------
- // 3 variables
- $d = null;
- $e = null;
- if($a && $b && $c && !$d && !$e){
- doSomething('dds', $a, $b, $c);
- }
- /* OUTPUT:
- Decimal: 10
- Decimal: 20
- String: hello */
- echo '<hr>';
- // ------------- CASE 4 ---------------------------
- // I want to have a more generic approach.
- $argumentList = array(
- 'a' => 10,
- 'b' => 20,
- 'c' => null,
- 'd' => null,
- 'e' => null,
- );
- $argumentList = array_filter($argumentList);
- $actionStr = '';
- foreach($argumentList as $k => $v){
- if(is_numeric($v)){
- $actionStr .= 'd';
- }
- if(is_string($v)){
- $actionStr .= 's';
- }
- }
- $varList = array_values($argumentList);
- $param_arr = array();
- $param_arr[] = $actionStr;
- $param_arr = (array_merge($param_arr, $varList));
- call_user_func_array('doSomething', $param_arr);
- /* OUTPUT:
- Decimal: 10
- Decimal: 20 */
Add Comment
Please, Sign In to add comment