1

I have an array as $arr = array("name" => "Fom Xong" , "Sales" => "100");

From this array I want to generate a string something like this

$str = 'name="Fom Xon" Sales="100"';

Is it possible???

thanks in advance

6
  • 4
    @Shakti Singh: stackoverflow.com/questions/4529640/… --- when you asked rtfm-like question you had had got polite and specific answers ;-) Commented May 23, 2011 at 6:12
  • 1
    @zerkms: That is not like rtfm question. I came up with the specific problem and that's why the question got 4 upvote Commented May 23, 2011 at 6:15
  • 1
    @Shakti Singh shame, actually you failed to generate an answer so you get angry by yourself Commented May 23, 2011 at 6:16
  • 3
    @Shakti Singh: 1) OP asked also specific problem (how to transform source array into the specifically formatted string). The difference between him and you is that he is a newbie and you are not 2) Number of upvotes doesn't mean either the question is good or bad, usually at SO amount of upvotes is caused by phase of the Moon. Commented May 23, 2011 at 6:18
  • @zerkms: My question is pointing a specific problem which is how to get year from date when year is above 2038. Which is not like rtfm and will helps community Whereas this question is completely leading someone to learn, read array basics and how to iterate arrays. That makes a big difference between my question and this question. Thanks Commented May 23, 2011 at 6:27

2 Answers 2

3

For example you can do like this:

$tmp_arr = array();
foreach ($arr as $key => $val)
  $tmp_arr[] = $key.'="'.$val.'"';

$str = implode(' ', $tmp_arr);
Sign up to request clarification or add additional context in comments.

3 Comments

You get the +1, only because I avoid expanding variable strings in PHP whenever I can. : )
Thank you boss. God give you a baby!
@John I knew I should've used sprintf('%s="%s"', $key, $value)... ;)
1
$output = array();
foreach ($arr as $key => $value) {
    $output[] = "$key=\"$value\"";
}
echo join(' ', $output);

Or:

echo join(' ', array_map(function ($key, $value) { return "$key=\"$value\""; }, array_keys($arr), $arr));

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.