Explode & values and put them in an array

Hi All,

I’m confused how to explode on a set of values and then put them in an array.

So I have my code to query the database:


// Query Database
$sql_result = mysql_query("SELECT codes FROM tble") or trigger_error('Query failed: ' . mysql_error());
$string_with_pipes = mysql_result($sql_result,0);

// Explode on pipes called from the db eg: |12|108|123|12|
$site_nums = explode("|",$string_with_pipes);

// Now what I want to do is after this is somehow use these values in
// $site_nums and put them in an array
// this is where I am stuck?

//Then I can use the array
foreach ($site_nums as $site_num) { 

//Do stuff

}


Thanks

Er, [fphp]explode[/fphp] returns an array. So $site_nums should be an array already. :wink:

Thanks, I thought that was the case but wanted to check I was not going crazy.

So i’m a little confused.

The code:


// Query Database
$sql_result = mysql_query("SELECT codes FROM tble") or trigger_error('Query failed: ' . mysql_error());
$string_with_pipes = mysql_result($sql_result,0);

// Explode on pipes called from the db eg: |12|108|123|12|
$site_nums = explode("|",$string_with_pipes);


// PRINT THE ARRAY
print_r ($site_nums);

Returns:

Array ( [0] => [1] => 12 [2] => 108 [3] => 123 [4] => 12 [5] =>

So immeiately after when I run my foreach:



foreach ($site_nums as $site_num) { 

 $SQL = "SELECT * FROM othertable WHERE site_id = ".$site_num.""; 
 print $SQL;
}


$site_num is empty?

Thanks

Database normalisation aside (and it needs it :)), it looks like you have some empty elements.

This should get rid of those for you.


<?php
$site_nums = array_filter(
    (array)explode(
        '|',
        $string_with_pipes
    )
);
?>

Thanks - worked a treat