简体   繁体   中英

PHP how to loop through assoc array without replicating variables?

This would be easy to do with regular array with a simple for statement. EG:

    $b= array('A','B','C');
    $s=sizeof($b);
    for ($i=0; $i <$s ; $i++) $b[$i]='your_face';
    print_r($b);

But if I use assoc array, I can't seem any easy way to do it. I could, of course use a foreach loop, but it is actually replicating the $value variables instead of returning a pointer to an actual array entity. EG, this will not work:

    $b= array('A'=>'A','B'=>'B','C'=>'C');
    foreach ($b as $v) $v='your_face';
    print_r($b);

Of course we could have some stupid idea like this:

    $b= array('A'=>'A','B'=>'B','C'=>'C');
    foreach ($b as $k => $v) $b[$k]='your_face';
    print_r($b);

But this would be an awkward solution, because it would redundantly recreate $v variables which are never used.

So, what's a better way to loop through an assoc?

You could try:

foreach(array_keys($b) as $k) {
    $b[$k] = 'your_face';
}

print_r($b);

See the following link for an explaination of array_keys : http://php.net/manual/en/function.array-keys.php

不知道这是否是您想要的,但是这里是:

foreach(array_keys($b) as $k) $b[$k] = 'your_face';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM