Jump to content


Arrays and Foreach

  • Please log in to reply
2 replies to this topic

#1 sanfly

  • Members
  • PipPipPip
  • Advanced Member
  • 344 posts
  • LocationNew Zealand

Posted 03 May 2006 - 09:12 AM

Lets say I have the following array

Array ( 
[b_name] => Array ( [0] => Naquadah [1] => Remote [2] => These Four Walls ) 
[b_web] => Array ( [0] => www.naquadah.co.nz [1] => www.remote.net.nz [2] => www.thesefourwallsband.com ) 

I want to use a foreach loop to get the data out, but im not quite sure how to execute it properly. Below is how I imagined the loop would go, but obviously not working

// Insert the bands into the database
    $bands = array();
    $bands['b_name'] = $b_name; // The Band names in an array
    $bands['b_web'] = $b_web;  // The Band websites in the array
    foreach($bands as $val){
            $b_name = addslashes($val['b_name']);
            $b_web = $val['b_web'];
            //$b_web = addslashes(validateWeb($b_web));
            // insert goes here

Can anyone help me figure out how it should really go?
If you're not part of the solution, you're part of the precipitate

#2 ober

  • Staff Alumni
  • Advanced Member
  • 5,337 posts
  • LocationEast Coast, USA

Posted 03 May 2006 - 12:28 PM

Well, first of all, you need to look at your design. What you're doing with a single array doesn't really make sense. You need to use either a 2 dimensional array or use 2 arrays.

I'm not sure why you're sticking them into an array before you dump them into the database either. If that's coming from some multi-listing form, you could easily setup the form to pass an array to the processing page.

I'm also not sure if a foreach is what you really want to do here... a simple for loop would get the job done.

But here is the syntax for a foreach loop:
foreach($arrayname as $key => $val)
     // $key is the index of the array
     // $val is the value at that index

Info: PHP Manual

#3 emehrkay

  • Staff Alumni
  • Advanced Member
  • 1,214 posts

Posted 03 May 2006 - 12:42 PM

i cannot figure out a way for you to loop that data, but to access it i think you would have to do something like this


0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users