Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I'm trying to build a SQL query by looping in PHP using 2 arrays (one of which is array of arrays):

    //build array of arrays using predefined arrays
$regions = array_filter(array($EAPRO, $WCARO, $ROSA, $TACRO, $MENA, $ESARO));

//just a normal array
$regionnames = array('EAPRO', 'WCARO', 'ROSA', 'TACRO', 'MENA', 'ESARO');

$sql = "";

foreach(array_combine($regions, $regionnames) as $region => $regionname)
{
$sql .="UPDATE `database`.`table` SET `region`='$regionname' 
WHERE `countryname` IN (" . implode(",",$region) . ");";
}
echo $sql;

However, debugging this in ideone gives me:

Warning: implode(): Invalid arguments passed on line:
UPDATE `database`.`table` SET `region`='ESARO' WHERE `countryname` IN ();

Which tells me that the array on each loop is not being imploded correctly. Is there something wrong with the way I've defined my array of arrays?

Thanks

share|improve this question
    
is $region defined ? I don't think so, so try implode(",",$regions) –  HamZa Oct 21 '12 at 22:48
    
Hmm, $region should be defined by the loop: foreach(array_combine($regions, $regionnames) as $region => $regionname) so on any given loop $region should be set to one of the arrays defined in $regions no? –  Gideon Oct 21 '12 at 22:52
    
my bad it slipped from my sight ... –  HamZa Oct 21 '12 at 22:57
    
No probs :) thanks for looking. –  Gideon Oct 21 '12 at 22:57
    
Hmmm didn't you "flip" in array_combine($regions, $regionnames) the variables ? From the docs it's said php.net/manual/en/function.array-combine.php: array array_combine ( array $keys , array $values ). Try array_combine($regionnames, $regions) –  HamZa Oct 21 '12 at 23:00

1 Answer 1

up vote 1 down vote accepted

From the PHP Docs: array_combine ( array $keys , array $values )

So the problem is that the variables are in the wrong places array_combine($regions, $regionnames) (a key can never be an array).

So this should fix the problem:

    //build array of arrays using predefined arrays
$regions = array_filter(array($EAPRO, $WCARO, $ROSA, $TACRO, $MENA, $ESARO));

//just a normal array
$regionnames = array('EAPRO', 'WCARO', 'ROSA', 'TACRO', 'MENA', 'ESARO');

$sql = "";

foreach(array_combine($regionnames, $regions) as $region => $regionname)
{
$sql .="UPDATE `database`.`table` SET `region`='$regionname' 
WHERE `countryname` IN (" . implode(",",$region) . ");";
}
echo $sql;
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.