0

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';
}
air4x
  • 5,618
  • 1
  • 23
  • 36
mko
  • 21,334
  • 49
  • 130
  • 191

2 Answers2

1

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);

Alternative #1

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
}

Alternative #2

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.



Alternative #3 (don't modify source array)

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

Filip Roséen - refp
  • 62,493
  • 20
  • 150
  • 196
  • 1
    post written using my blackberry, currently traveling and my charger for my macbook broke... Sorry for any minor mistakes (if any). – Filip Roséen - refp Oct 20 '12 at 05:50
  • @yozloy if you find the post content helpful please up-vote the post, and if it helped you solve your problem please mark it as "accepted". (It will make users more eager to answer your posts in the future, as well as helping readers of this thread who skims through it) – Filip Roséen - refp Oct 20 '12 at 11:54
0

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';
}
air4x
  • 5,618
  • 1
  • 23
  • 36