2

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!

three3
  • 2,756
  • 14
  • 57
  • 85

4 Answers4

2

easiest would just use a foreach statement:

foreach($yourarray as $array_element) {
  $address = $array_element['address'];
  $fname   = $array_element['fname'];
  ...
}
kennypu
  • 5,950
  • 2
  • 22
  • 28
2

you can do this by

foreach($array as  $value) {
   foreach($value as  $val) {
    echo $val;
  }
}
NullPoiиteя
  • 56,591
  • 22
  • 125
  • 143
2

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.

mr-sk
  • 13,174
  • 11
  • 66
  • 101
1

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;
}
Austin Brunkhorst
  • 20,704
  • 6
  • 47
  • 61