FOREACH with Logical Operator

Discussion in 'PHP' started by mayankoneman, Dec 3, 2010.

  1. #1
    hi,
    can i use && in foreach loop

    for example -

    foreach ($_POST['day'] as $day && $_POST['event'] as $event)
    {
    $query = "INSERT INTO event(year,day,event) VALUES('$_POST[year]','$day','$event')";
    }
    PHP:
    but it is giving error

    Parse error: syntax error, unexpected T_BOOLEAN_AND, expecting ')' 
    Code (markup):
    if it is incorrect tell me the right code please.

    thanks
     
    mayankoneman, Dec 3, 2010 IP
  2. drctaccess

    drctaccess Peon

    Messages:
    62
    Likes Received:
    1
    Best Answers:
    1
    Trophy Points:
    0
    #2
    Assuming that $_POST['day'] and $_POST['event'] are arrays use the code below...

    
    <?php
    $_POST['day'] = array('S','M','T','W','T','F','S');
    $_POST['event'] = array('ev1','ev2','ev3','ev4','ev5','ev6','ev7');
    $_POST['year'] = 2010;
    
    foreach($_POST['day'] as $key => $day)
    {
            foreach($_POST['event'] as $event)
            {
                    $query = "INSERT INTO event(year,day,event) VALUES('$_POST[year]','$day','$event')";
                    print_r($query);
                    echo "\n";
            }
    }
    ?>
    
    Code (markup):
    if they are not arrays then using of foreach is useless .. you can just use the code below:

    
    <?php
    $_POST['day'] = 'Monday';
    $_POST['event'] = 'some event';
    $_POST['year'] = 2010;
    
    $query = "INSERT INTO event(year,day,event) VALUES ('$_POST[year]','$_POST[day]','$_POST[event]')";
    print_r($query);
    echo "\n";
    ?>
    
    Code (markup):
    I hope this helps
     
    drctaccess, Dec 4, 2010 IP
  3. imocoder

    imocoder Member

    Messages:
    45
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    43
    #3
    You cannot use logical operator inside foreach.
     
    imocoder, Dec 4, 2010 IP
  4. w47w47

    w47w47 Peon

    Messages:
    255
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #4
    you can do it like this:

    foreach ($_POST['day'] as $day)
    {

    $event=$_POST['event'];
    $query = "INSERT INTO event(year,day,event) VALUES('$_POST[year]','$day','$event')";
    }

    or if you have multiple events like this:

    you can do it like this:

    $i=0;
    foreach ($_POST['day'] as $day)
    {
    $event=$_POST['event'][$i];
    $query = "INSERT INTO event(year,day,event) VALUES('$_POST[year]','$day','$event')";
    $i++;
    }
     
    w47w47, Dec 6, 2010 IP