2
votes

I am having trouble trying to loop through a multidimensional array using PHP. When I use the print_r() function, here is my output:

Array ( [0] => Array ( [fname] => [sname] => [address] => [address2] => [city] => [state] => Select State [zip] => [county] => United States [phone] => [fax] => [email] => [use_email] => on )

I have tried several techniques but none seem to work. Any help is appreciated!

4

4 Answers

2
votes

easiest would just use a foreach statement:

foreach($yourarray as $array_element) {
  $address = $array_element['address'];
  $fname   = $array_element['fname'];
  ...
}
2
votes

you can do this by

foreach($array as  $value) {
   foreach($value as  $val) {
    echo $val;
  }
}
2
votes

Your code is:

$set = array( 0 => array ( 'fname' => '',
                             'sname' => '',
                             'address' => '',
                             'address2' => '',
                             'city' => '',
                             'state' => 'Select State',
                             'zip' => '',
                             'county' => 'United States',
                             'phone' => '',
                             'fax' => '',
                             'email' => '',
                             'use_email' => 'on')
);

$subArray = $set[0]; // <-- key line
foreach($subArray as $k => $v) {
    printf("key: %s, value: %s\n", $k, $v);
}

Output:

key: fname, value: 
key: sname, value: 
key: address, value: 
key: address2, value: 
key: city, value: 
key: state, value: Select State
key: zip, value: 
key: county, value: United States
key: phone, value: 
key: fax, value: 
key: email, value: 
key: use_email, value: on

You need to access the indexed array properly.

1
votes

It looks like there is one more dimension before what you want to loop through. Try this.

foreach($array[0] as $key => $value) {
    echo $key, ': ', $value;
}