0

I have a key-pair array like this

$option['33']="Steak Doness";
$option['34']="Size";
$option['35']="Cooking Method";

I want to store the keys into a string like this

$key="33,34,35,";

I try to use foreach loop

$key="";

foreach($option as $key => $value) {
    $key=$key.",";
}
echo $key;

However, my output is

35,

May i know which part went wrong?

1
  • 1
    just try echo $key = implode(",", array_keys($option)). Commented Sep 29, 2016 at 11:21

2 Answers 2

1

You miss use the $key in your script.

The problem is with the $key which is in the foreach loop.... In each time your $key variable updated with the loop... Try with difference variable in your script.

OR, simply use

echo $key = implode(",", array_keys($option));
Sign up to request clarification or add additional context in comments.

1 Comment

Technically echo $key = implode(",", array_keys($option)).','; if you want to produce the exact output OP is showing.
0

1st change your varible $key to $keys replace one line

$key=$key.",";

to

$keys .= $key . ",";

it will work 100%

6 Comments

what is the logic of these?? If i add the key each time and store in the same variable then is there anything wrong?? **The problem is with the $key which is in the foreach loop...
you are re-assigning $key every time but you need to concat it so :)
You misunderstood, Just take a look.. there are 2 $key, One is in the foreach loop and another is to store the keys..
your coding its not working. plz check. Frayne's one is working
@FrayneKonok used implode function that will produce output like 33,34,35 not like 33,34,35,
|

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.