I need to insert more than one row in a table
foreach($answers as $answer){
$sql =<<<EOD
INSERT INTO answer(`answer`, `question_id`)
VALUES ('$answer', (SELECT `id` FROM question WHERE `title` = '$title'))
EOD;
result_array[] = $this->db->query($sql);
}
I need to check each insert query is return True
. What's control structure in Php can let me do something like:
if(each_value in result_array == 'True'){
return 'success';
}
To make sure that you only have booleans in your array double negate the values returned by your query function (unless it already returns true/false, of course).:
result_array[] = !! $this->db->query($sql);
You could find the unique values between array(true)
and your resulting array (result_array
) and then see if the size is equal to zero using array_diff
:
if (sizeof (array_diff (result_array, array (true)) == 0) {
// all went well
}
If your resulting array only consists of values of either true
or false
you could hack your way through it using array_product
such as in the below:
var_dump (array_product (array (true, false, true)));
var_dump (array_product (array (true, true, true)));
Output
int(0)
int(1)
array_product
will multiply all the values of the array with each other, and since true
evalutes to the integer 1 and false
to the integer 0 we can use this to our advantage.
You could use array_reduce
with a callback to reduce your array to a single value, such as:
if (array_reduce (result_array, function ($a,$b) {return $a && $b;}, true) == true) {
// all went well
}
This will implicitly cast every value of your array to a boolean, and give you the result you are after.
inline lambdas require more recent versions of PHP, a regular function name can be used as a callback if lambdas are unavailable
If the values in the array are string
True
and not boolean
true
you can use this, else use array_product
as in the other answer.
$res = array_unique($your_array);
if (sizeof($res) === 1 && current($res) == 'True') {
return 'success';
}