1

I know this question is simple, but I have little experience with arrays and am having difficulty. Anyway I have this array:

$variables=array("$value1" => "int",$value2 => "var",$value3 => "int");

I want to cycle through it and for each $value I would like to add

$stmt->bindValue(1,$value, PDO::PARAM_INT); if $value is 'int' or

$stmt->bindValue(1,$value); if $value is 'var'

and have the '1' increase as it cycles through the variables. Does anyone know how to do this?

3
  • 1
    post the code you have tried. This is a simple foreach with an if Commented Jun 21, 2011 at 21:20
  • Your question doesn't make sense. if $value is 'var'? you mean string? Add? you mean numerically add? or concatenate? Please improve your question. Commented Jun 21, 2011 at 21:21
  • Everyone else seemed to understand just fine. Is English not your native tongue or are you just hating for no reason? Commented Jun 21, 2011 at 21:31

3 Answers 3

2

Maybe something like this:

$count = 1;
foreach ($variables as $key => $value){

  switch ($value) {
        case "int":
            $stmt->bindValue($count, $value, PDO::PARAM_INT); 
          break; 

        case "var":            
            $stmt->bindValue($count, $value);      
         break;

        default:
           exit("Invalid value");            

    }                
          $count++; 

}
Sign up to request clarification or add additional context in comments.

3 Comments

+1 switch can also be a good way if there can be further cases. An exit seems a bit strict though ;).
The exit is indeed a showstopper, it was put there just to show op he can easily have a block to handle unexpected conditions! Thanks for pointing that out.
Thanks for the contribution stef +1.
1

A foreach loop lets you loop through your array. The foreach ($array as $k=>$v) syntax lets you define a variable to hold the current key ($k) and one for the current value ($v). I also used a simple variable that is incremented in every cycle ($i).

Then a simple if-elseif combo is used to do something different.

$i=1;
foreach ($variables as $k=>$v) {
    if ($v=='int') {
        $stmt->bindValue($i, $k, PDO::PARAM_INT);
    }
    elseif ($v=='var') {
        $stmt->bindValue($i, $k);
    }
    $i++;
}

This can be optimized further, I wanted to show the logic.

Comments

1

Simple loop should do it

$x=0;
foreach($variables as $key=>$value)
{
  if($value=="var")
   {
     $stmt->bindValue($x,$key);
   }
   else
   { 
      $stmt->bindValue($x,$value, PDO::PARAM_INT);
   }
  $x++;
}

1 Comment

You need the key in bindValue, not the value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.