-1
array(7) {
  [0]=>
  array(2) {
    ["name"]=>
    string(14) "form[username]"
    ["value"]=>
    string(1) "1"
  }

  [1]=>
  array(2) {
    ["name"]=>
    string(15) "form[is_active]"
    ["value"]=>
    string(1) "1"
  }

  [2]=>
  array(2) {
    ["name"]=>
    string(8) "form[id]"
    ["value"]=>
    string(1) "9"
  }
 }

I want to get the id from an array. The output I like to achive is 9.

My approach:

echo $array['form[id]'];

But I don't get an output.

peace_love
  • 6,229
  • 11
  • 69
  • 157

5 Answers5

4

When you use $array['form[id]']; you are looking for the key called 'form[id]' which will not work because the keys of your array are 0, 1 and 2. You can get your desired value by using $array[2]['value']. However this will always call the 2nd element of your array, which might not be what you want. A more dynamic solution would be something like this:

foreach ($array as $element) {
    if ($element['name'] == 'form[id]') {
        echo $element['value'];
        break;
    }
}

This will loop through your whole array and check the names of each element. Then when it matches your desired name it will print the value for that exact element.

Dirk Scholten
  • 1,013
  • 10
  • 19
3

The easiest way might be to just first re-index the array using array_column. Then you can use the name field as the key:

$array = array_column($array, null, 'name');

echo $arr['form[id]']['value'];
// 9

See https://3v4l.org/L1gLR

iainn
  • 16,826
  • 9
  • 33
  • 40
  • that is the way to go :), although i dont find any need to use array like him, he can simply do like https://3v4l.org/puGKm – NullPoiиteя Aug 15 '18 at 10:17
2

You could use a foreach and check for the content .. but the content for index 'name' is just a string form[id] anyway

foreach( $myArray AS $key => $value){

   if ($value['name'] == 'form[id]' ) {
      echo $key;
      echo $value;

   }


}
NullPoiиteя
  • 56,591
  • 22
  • 125
  • 143
ScaisEdge
  • 131,976
  • 10
  • 91
  • 107
1

You are trying to get the value as if it's an associative array (sometimes called a dictionary or map), however it's a plain or indexed array.

Get the value you want by calling $array[2]["value"]

You can also use some of the higher level functions such as array_search; then you could use:

$id = array_search(function($values) {
  return $values['name'] == 'form[id]';
}, $array)["value"];
Erik Terwan
  • 2,710
  • 19
  • 28
0

So I think you need to filter the array to find the element you need first, then output that element's value:

$filtered_array = array_filter($your_array, function(element){
   return element['name'] == 'form[username]';
});

if (!empty($filtered_array)) {
   echo array_pop($filtered_array)['value'];
}
Thien
  • 31
  • 5