Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array initialisation with value

Tags:

php

Hello guys i have coded something like this ..I just dont know wheather the code is right or not ..But i have a question

THe code is

$featured = array('name' => 12,'yeah' => 10);
foreach($featured as $key => $value){
  echo $value['name'];
}

I know that value of name can be acessed by $featured['name'] but now I just need to know wheather the key of array can be acessed with value like $value['name']. Is it possbile like that ?..

Any help would be appreciated ..Thanks

like image 758
user3288826 Avatar asked Mar 29 '26 00:03

user3288826


2 Answers

$featured = array('name' => 12,'yeah' => 10);
foreach($featured as $key => $value){
  echo $key; // outputs: name
  echo " - ";
  echo $value; // outputs: 12
  echo "<br />";
}

Yes, it supports that in the next iteration of the loop.

Output:

name - 12
yeah - 10

BTW, one more way of accessing the keys from array.

$featured = array('name' => 12,'yeah' => 10);
while (current($featured)) {
  echo key($featured).'<br />';
  next($featured);
}

Output:

name
yeah
like image 186
Dmytro Dzyubak Avatar answered Mar 31 '26 05:03

Dmytro Dzyubak


You most probably want to do:

echo "{$key} => {$value}";

The foreach($featured as $key => $value) statement iterates the array and for each iteration $key and $value contain both the key and value for the tuple.

like image 31
bbonev Avatar answered Mar 31 '26 03:03

bbonev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!