0

I am new to PHP, And am creating a data string, which i have written like this.

$data = $product['id']. "/" . $product['name'] . "/" .$product['price'];

I don't know if there is another better way to create this String.

3
  • Hello. What do you feel as "worse" (wrt "better") in this way of doing things ? Commented Dec 22, 2010 at 9:35
  • I don't know if this good or bad is. Commented Dec 22, 2010 at 9:36
  • you can also use single quotes: sematopia.com/2007/08/php-double-quotes-vs-single-quotes Commented Dec 22, 2010 at 9:38

5 Answers 5

4

It looks like a perfectly fine way to concatenate strings in php.

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

Comments

2

PHP can interpolate array values inside double quotes if they are surrounded with {}:

$data = "{$product['id']}/{$product['name']}/{$product['price']}";

If you remove the quotes around the keys you don't need the curly braces and it will become even simpler:

$data = "$product[id]/$product[name]/$product[price]";

3 Comments

I disagree on the readability. The OP solution is imho perfectly fine.
This is much more readable: $data = "$product[id]/$product[name]/$product[price]";
@Maris: Wouldn't not enclosing the key in quotes lead to an E_NOTICE error?
1

So simple task cannot be wrong. You can concatenate strings in any way you want.

I usually prefer same style as you wrote in your example.

Comments

1

You could use sprintf for it, which has the advantage of giving a better overview:

sprintf('%d/%s/%f', $product['id'], $product['name'], $product['price']);

Comments

0

Other way:

$data  = "Name";
$date .= $product['id'];
$date .= "AND etc..";

1 Comment

This is wors in a performance way and also wrong in that it will not create the same string as the example.

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.