PhP Array how to get a value of a key

2019-09-20 17:21发布

I have a php array, $vararray, like so

[var1] => 1
[var2] => 1
[var3] => 1
[var4] => 1
[var5] => 2
[var6] => 2
[var7] => 1
[var8] => 1

After a bunch of operations i get a key/index of var8. How do I get value of var8 using the key? I can get the key using array key function. But is there a function for array value? I checked php manual but didnt seem to find any.

标签: php arrays loops
4条回答
Fickle 薄情
2楼-- · 2019-09-20 17:41

You can access it like this:

$value = $vararray['var8'];

Or you can loop over the array using a foreach loop: http://php.net/manual/en/control-structures.foreach.php

foreach ($vararray as $value) {
    echo $value;
}
查看更多
姐就是有狂的资本
3楼-- · 2019-09-20 17:44

Accessible like this

$var8Value = $vararray['var8'];
查看更多
疯言疯语
4楼-- · 2019-09-20 17:45

If $key contains the key you're interested in (e.g. var8) you use

$vararray[$key]

to access the value of the corresponding element.

查看更多
做个烂人
5楼-- · 2019-09-20 17:47

For getting all keys value like $var1, $var2, $var3, .... Try this

foreach($vararray as $key=>$val){
    $$key = $val;
}
echo $var1;
echo $var2;
echo $var3;
echo $var4;
echo $var5;
echo $var6;
echo $var7;
echo $var8;
查看更多
登录 后发表回答