Creating arrays from MySQL Selects in PHP

I lost about an hour of my life to this last night, so I thought I would post the solution here in case anyone else was having a similar problem.

I was working on a library I wrote some time ago for rendering forms, and I needed to double check if a value was in an array. I was doing a sub select in a MYSql query that looked like this:

(select GROUP_CONCAT(experienceid SEPARATOR ',') from e_industryexperiencemap) as industryexperience

which would turn a CSV list of values, such as ‘12,4,1,4’

Let’s assume that I placed those values in a variable called $SelectedIDs. I was then doing this:

$SelectedIDs = array($SelectedIDs);

Where I turn $SelectedIDs into an array so I can use in_array to check if a value is present. Such as:

if (in_array($IDtoCheck, $SelectedIDs)) {
     echo ‘success’;
} else {
     echo ‘not present’;
}

//$IDtoCheck = 12;

Now, the problem I was having is that no matter what I did I could never get in_array to return TRUE, even though I knew the values were correct. Took me awhile to figure it out, but the problem was this:

Since the list came out of a database it was a string, and translated as this:

$SelectedIDs = array($SelectedIDs);
// or $SelectedIDs = array('12,4,1,4');

Which produces an index array with one value ([0] => “12,4,1,4”). Which doesn’t work with my in_array statement (12 is not equal to 12,4,1,4 so it always returns false).

However, if I use ‘explode’ it would produce an array such as: ([0] => “12”, [1] =>”4” ….). Which when using in_array would give me my boolean value of TRUE (e.g. 12=12).

To be safe, you can also convert the needle element of in_array to a string. So you would end up with this:

$SelectedIDs = explode(",",$SelectedIDs);

if (in_array(strval($IDtoCheck), $SelectedIDs)) {
     echo 'success';
} else {
     echo 'not present';
}

//note the strval() around $IDtoCheck which you might want to play around with or remove

31 notes

Show

  1. wickedbrilliant posted this

Blog comments powered by Disqus