lets say i have a function add().
function add(){
if (a)
return true;
if (b)
return true;
if (c)
insert into table.
return true;
}
now i call this function add() and i want to increment my counter only if there is insert execution like condition C. I also don't want to change the return value which is true. Now my question is how can i find out if section C is executed? I thought i can use a global variable in condition c like below
if (c)
{
insert into table.
$added = true;
return true;
}
and then i check
if(isset($added && $added==true))
$count++;
but i would like to know if there is any parameter i can add or some other approach i can use?
Add an if around your insert, and add a counter as a parameter:
$count = 0;
function add(&$count){
if (a)
return true;
if (b)
return true;
if (c)
if(insert into table){ //Queries return a boolean
$count++;
}
return true;
}
add($count); //If insertion was succesful it added 1 to counter.
echo $count; //Returns either 1 or 0 depending on insert statement.
You can pass a parameter by reference. In PHP, this is done by prepending a pound sign (&
). The result is that your function doesn't get a copy of the value but a variable refering the original value, so you can change it inside your function.
function add(&$itemsAdded)
{
$itemsAdded = 0;
[...]
/* if added something */
$itemsAdded++;
}
in your calling code
add($added);
$counter += $added;