For loop string concatination

This is driving me nuts I am so close. Please help!!

I made a web page with a few drop down boxes. some of which have a selection of ALL.

I have a js array like
sitesArray = [1,2,3,4,5,6]
I turn the js array into a comma delimited string: var sitesStr = sitesArray.join(‘,’)
and I use jquery to post the string to PHP.

On the PHP side:

I grab the post variable and turn it into a php array:
$siteArray = explode(‘,’,$_POST[‘sitesStr’]);

This is to be used in the where clause of a sql query.
Calling one variable from the array works.
$position = “pl.position = '” . $siteArray[5] . "’ ";
Output is 6

Trying to append string to a variable behaves unexpectedly.


<?php

$siteArray = explode(',',$_POST['sitesStr']);
$position = sites($siteArray);

function sites($siteArray) {
  $position = "( ";
  for ($i=0; $i > count($siteArray); $i++) {
    if ($i == 0) {
      $position .= "pl.position = '$siteArray[$i]' ";
    } else {
      $position .= "or pl.position = '$siteArray[$i]' ";
    }
  }
  $position .= " )";
  return $position;
}
?>

the function returns ( ) like it completely ignores the appending of the for loop!!!

Where did I go wrong???

Thanks

I would write it like this:

$siteArray = explode(',',$_POST['sitesStr']);
$conditions=implode(' or ',$siteArray);
$position = "(".$conditions.")";

E

if done this way wouldn’t the implode put an or on every element in the array? cause the ’ or ’ needs to be left off the first element

You have the following line:

for ($i=0; $i > count($siteArray); $i++) {

At the start of the loop, $i is set to zero. Then the condition is checked, is $i greater than the number of items in the array? No, it never will be! Since the condition is not true, the loop contents never get executed.

A simple mistake, just flip the operator around to be less than ($i < count(&#8230;)).

P.S. Welcome to Sitepoint, jbarby. (:

Nope. Its a delimiter so it would only show between the elements.
The code example needs a little adjustment, but that’s the basic idea.

E

Ah good to know :slight_smile: Thanks

:headbang: Figures it would be something simple like that.

Thank you!!! I was staring for hours trying to figure out why it was not working.