1

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?

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

Yep, this looks much better. I will accept it as the first answer then. Thanks :)
2

Not sure if that's what you want, but here goes:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.