In the context of the following tutorial:
An easy way to allow a variable number of parameters is to set defaults for all but the first two:
function my_add( $val1, $val2, $val3 = '', $val4 = '', $val5 = '' ){ return $val1 + $val2; }You can try something like below to make sure the values are numeric, otherwise return 0:
function my_add( $val1, $val2, $val3 = '0', $val4 = '0', $val5 = '0' ){ if( !is_numeric( $val1 ) || !is_numeric( $val2 )){ // add checks for all the values return 0; } return $val1 + $val2; }
I have attempted to adapt the above code for my own purposes - though the code may be erroneous, I believe the intention is clear:
function sum_warehouses_stock( $warehouse1, $warehouse2, $warehouse3 = '0', $warehouse4 = '0', $warehouse5 = '0' ){
if( !is_numeric( $warehouse1 ) {
$warehouse1 = 0;
}
if( !is_numeric( $warehouse2 ){
$warehouse2 = 0;
}
if( !is_numeric( $warehouse3 ){
$warehouse3 = 0;
}
if( !is_numeric( $warehouse4 ){
$warehouse4 = 0;
}
if( !is_numeric( $warehouse5 ){
$warehouse5 = 0;
}
return $warehouse1 + $warehouse2 + $warehouse3 + $warehouse4 + $warehouse5;
}
But I get:
Parse error: syntax error, unexpected ';' in your code on line 26
- Can you help me correct the error?
- How can I improve my code to be more efficient as I realise there is a lot of repetition?
Edit 1: to spell out the intention the function should check all of these variables and ensure for each variable that if their value is not numerical, redefine their values to zero. Then sum the values of the variables.
Edit 2: The solution needs to be in the format function ($warehouse1, $warehouse2, $warehouse3) but such that it is expressed in a more generally as: function (/* array of a variable number of warehouses*/)
Edit 3 - this is the solution I've been running with based on kojow7's answer:
function ld_sum_warehouses_stock($a, $b, $c, $d, $e, $f){
$warehouses = array( $a, $b, $c, $d, $e, $f );
$total = 0;
foreach($warehouses as $warehouse){
$warehouse = str_replace(["+","<",">"], "", $warehouse);
if (is_numeric($warehouse)){
$total += $warehouse;
}
}
return $total;
}
It allows me to call on a single function and pass the relevant variables in a single call - which is a constraint of the plugin I'm using.
However, at this stage the code is inflexible and forces me to commit to fixed number of variables. If the above code can be re-written accommodate a variable number of variables $a, $b to $n, then the solution will finally be consummated.
)on the if blocks, time to get some coffee!is_numeric(). It (they) should beif ( !is_numeric($warehouseN) )(two final parenthesis).