3

I try to read some keys of an array like

array(3) {

["poste5:"]=> array(3) { [0]=> string(7) "APPLE:" [1]=> string(5) "demo1" [2]=> string(5) "demo2" }

["services:"]=> array(4) { [0]=> string(9) "orange" [1]=> string(5) "demo3" [2]=> string(5) "demo4" [3]=> string(5) "demo1" }

["essai:"]=> array(2) { [0]=> string(6) "sd" } }

I try to read this name : poste5 , services , essai

If i use :

foreach ($this->aliasRead as $key => $value){

echo array_keys($this->aliasRead[$key]);
}

I have : Array()

But if i use :

foreach (array_keys($this->aliasRead) as $key => $value2) {
       echo $value2;
}

I have poste5 , services , essai

I try to use with this loop foreach ($this->aliasRead as $key => $value){ because i have another traitment after. How to collect this key of my first loop in this loop foreach ($this->aliasRead as $key => $value){ ?

mpgn
  • 7,121
  • 9
  • 67
  • 100
  • I must admit I have problems to understand your question. If you need to collect something you normally store it into a variable in programming. However, I can't see that you make use of a variable here. So I'm a bit puzzled where you hit the roadblock. – hakre Jun 10 '13 at 12:23
  • And you have right, i correct that :) but i just want to have some opinion and explication ;) – mpgn Jun 10 '13 at 12:25

3 Answers3

1

Try this,

$keys = array_keys($this->aliasRead);
print_r($keys);

Or

$keys = array();
foreach ($this->aliasRead as $key => $value){
 $keys[] = $key;
}
Nikhil Mohan
  • 891
  • 6
  • 13
1

It's because you're trying to echo an array. This will always give you the string "Array". If you want to see the array's contents, try

var_dump(array_keys($this->aliasRead[$key]));

By the way, in the foreach statement you posted, $this->aliasRead[$key] will be the equal to $value. So this will work as well:

var_dump(array_keys($value));
Rijk
  • 11,032
  • 3
  • 30
  • 45
1

You already have what you want here:

foreach ($this->aliasRead as $key => $value){
    echo $key; // key of the value in the array
    print_r($value); // value of $this->aliasRead[$key] which in turn is another array
}

Edit: The reason your second loop works is because of this: array_keys($this->aliasRead[$key]) returns a new array containing the keys of the old array as its values. So $myNewArray = array_keys($this->aliasRead[$key]) is the same as $myNewArray = array('poste5','services','essai'). So, when you loop over this new array like this:

foreach ($myNewArray as $key => $value2) {
    echo $value2;
}

$value2 contains your values, which are the keys of your first array, and $key will be 0, 1 and 2 after each step through the loop.

stef77
  • 1,000
  • 5
  • 19