Jump to content

array in foreach loop


Twitch

Recommended Posts

Hello gurus,

 

I've been pounding my head against the wall on this one.  It must be something simple I'm missing.  I have a text field that posts ($_POST['case_ids']) a comma separated value such as 10067,10076  When I use explode to break it up it should make it an array.  However when I use it in a foreach loop I get an invalid argument error.  If I do a check for is_array() it fails the check. 

 

If I print the array I get:

Array ( [0] => 10067 [1] => 10076 ) 

 

So I thought maybe I get the error because the individual array elements don't have commas between them so I wrote this to put commas in between each element except the last:

$cases = array();
$numItems = count($case_ids);//get count of array
$i = 0;//initialize counter
foreach($case_ids as $key => $value){
if($i+1 != $numItems) {
$cases[$key] = $value.',';
}else{
$cases[$key] = $value;
}//end if $i+1
$i++;
}

 

However this new array still gets the invalid argument error.  Are these not valid arrays?

 

Any help would be greatly appreciated.

 

Thanks in advance,

Twitch

 

Link to comment
https://forums.phpfreaks.com/topic/248145-array-in-foreach-loop/
Share on other sites

Thanks for such a rapid reply, mikesta707.

 

The array I try to create from the posted comma separated values uses this code:

 

if (isset($_POST['case_ids'])){
$case_ids = mysql_real_escape_string($_POST['case_ids']);
$case_ids = explode(",", $case_ids);
        print_r($case_ids);

 

when I print_r($case_ids) then I get the aforementioned:

Array ( [0] => 10067 [1] => 10076 ) 

 

The foreach loop is similar to below (I simplified the $html so the code is more compact.  The actual $html that is echo'd is longer)

 

foreach($case_ids as $key => $value){//$key is not necessary but I included as troubleshooting step
mysql_select_db($database_db, $db);
$query_case = "SELECT case_name FROM cases WHERE case_id = '".$value."'";
$case = mysql_query($query_case, $db) or die(mysql_error());
$row_case = mysql_fetch_assoc($case);
$totalRows_case = mysql_num_rows($case);

$html = '<a href="somewhere.php">';
$html .= $row_case['case_name'];
$html .= '</a><br />';

echo $html;
}

 

Thanks again for the help.

 

-Twitch

Well after more testing I'm convinced my code is correct as well.  I was using this code to generate a PDF using mPDF and I'm thinking the issue is lying with the mPDF class because when I get rid of all mPDF code I don't get the invalid argument error.

 

Thanks for the reply, mikesta707.  Much appreciated.

 

-Twitch

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.