Jump to content

get keys of multi level array


php_guest

Recommended Posts

I am wondering what I am doing wrong in the following code, because I get error:

Warning: Illegal offset type in isset or empty in D:\xampp\htdocs\testing\4.php on line 5

 

$_POST[firstkey][secondkey]=12;
if (isset($_POST)) {
  foreach($_POST as $key){
    foreach ($_POST[$key] as $key2 => $value){
    echo "<br />Key=".$key2."value=".$value;
    }
  }
}

 

How would be the correct was echo in the same statement 1st and 2nd key and value?

 

Thank you

Link to comment
https://forums.phpfreaks.com/topic/163117-get-keys-of-multi-level-array/
Share on other sites

i don't think you can set an $_POST value manually??

i.e.

$_POST[firstkey][secondkey]=12; won't work?

 

what if $_POST array isn't multidimensional?

 

i'd do

if (isset($_POST)) {
  foreach($_POST as $key){
if (is_array($_POST[$key])) {
    foreach ($key as $key2 => $value){
    echo "<br />Key=".$key2."value=".$value;
    }
}
  }

 

oh, and what code is on line 5?

is it isset($_POST)?

 

and the second foreach should be

foreach $key as $key2 etc etc

 

i think you're problem was you were trying to use an array as an index.. i.e. $_POST[$key] when $key was an array.

use that

foreach $key as $key2 and you should be fine

I can not set it manually because I get it from previous page where names of inputs are set automatically.

... so you have a form on the previous page and its being posted to the page with the script you posted?

 

what are you trying to achieve by your foreach loops??

 

if you just want to look at the contents of the $_POST array you can use print_r($_POST);

 

have you tried this code? it *should* work

if (isset($_POST)) {
  foreach($_POST as $key){
if (is_array($_POST[$key])) {
    foreach ($key as $key2 => $value){
    echo "<br />Key=".$key2."value=".$value;
    }
}
  }

joel24 was referring to this line -

$_POST[firstkey][secondkey]=12;

 

And yes, you can set it manually. $_POST is an array afterall. Nothing really special about that. But people really need to learn to use better practices. When coding use error_reporting(E_ALL);. There is a PHP notice for using undefined constants as keys.

 

php_guest - joel24's code should work. If not, please explain your problem more clearly.

And yes, you can set it manually. $_POST is an array afterall. Nothing really special about that. But people really need to learn to use better practices. When coding use error_reporting(E_ALL);. There is a PHP notice for using undefined constants as keys.

 

interesting!

just had a play around you can even set $_SERVER['PHP_SELF'] etc etc..

always assumed they'd be locked...

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.