Guest User

Untitled

a guest
Jan 23rd, 2019
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.84 KB | None | 0 0
  1. function doSomething($actionStr, ...$args){
  2. $actionArr = str_split($actionStr);
  3.  
  4. foreach($args as $i => $n) {
  5.  
  6. switch ($actionArr[$i]) {
  7. case 'd':
  8. echo "Decimal: " . $n . '<br>';
  9. break;
  10. case 's':
  11. echo "String: " . $n . '<br>';
  12. break;
  13. default:
  14. break;
  15. }
  16. }
  17. }
  18.  
  19. // ------------- CASE 1 ---------------------------
  20. // In this case I have 5 arguments. So I can do this:
  21. $a = 10;
  22. $b = 20;
  23. $c = 'hello';
  24. $d = 'cheese';
  25. $e = 500;
  26.  
  27. if($a && $b && $c && $d && $e){
  28. doSomething('ddssd', $a, $b, $c, $d, $e);
  29. }
  30.  
  31. /* OUTPUT:
  32. Decimal: 10
  33. Decimal: 20
  34. String: hello
  35. String: cheese
  36. Decimal: 500
  37. */
  38.  
  39. echo '<hr>';
  40.  
  41. // ------------- CASE 2 ---------------------------
  42. // I'm using 4 variables
  43.  
  44. $e = null;
  45.  
  46. if($a && $b && $c && $d && !$e){
  47. doSomething('ddss', $a, $b, $c, $d);
  48. }
  49.  
  50. /* OUTPUT:
  51. Decimal: 10
  52. Decimal: 20
  53. String: hello
  54. String: cheese
  55. */
  56.  
  57. echo '<hr>';
  58. // ------------- CASE 3 ---------------------------
  59. // 3 variables
  60. $d = null;
  61. $e = null;
  62.  
  63. if($a && $b && $c && !$d && !$e){
  64. doSomething('dds', $a, $b, $c);
  65. }
  66.  
  67. /* OUTPUT:
  68. Decimal: 10
  69. Decimal: 20
  70. String: hello */
  71.  
  72. echo '<hr>';
  73.  
  74. // ------------- CASE 4 ---------------------------
  75. // I want to have a more generic approach.
  76.  
  77. $argumentList = array(
  78. 'a' => 10,
  79. 'b' => 20,
  80. 'c' => null,
  81. 'd' => null,
  82. 'e' => null,
  83. );
  84. $argumentList = array_filter($argumentList);
  85.  
  86. $actionStr = '';
  87. foreach($argumentList as $k => $v){
  88.  
  89. if(is_numeric($v)){
  90. $actionStr .= 'd';
  91. }
  92.  
  93. if(is_string($v)){
  94. $actionStr .= 's';
  95. }
  96. }
  97.  
  98. $varList = array_values($argumentList);
  99. $param_arr = array();
  100. $param_arr[] = $actionStr;
  101. $param_arr = (array_merge($param_arr, $varList));
  102. call_user_func_array('doSomething', $param_arr);
  103.  
  104. /* OUTPUT:
  105. Decimal: 10
  106. Decimal: 20 */
Add Comment
Please, Sign In to add comment