Reputation: 83
How would I print the following in one line?
$product_array = array(
"id" => 001,
"description" => "phones",
"type" => "iphone"
);
print "Print the product_array = ";
print_r($product_array);
Current result
Print the product_array =Array
(
[id] => 001
[description] => phones
[type] => iphone
)
Wanted Result
Print the product_array =Array ( [id] => 001 [description] => phones [type] => iphone )
Upvotes: 8
Views: 15992
Reputation: 41
just added some styleing:
echo ltrim(rtrim(str_replace(["\n",'Array(', "[", "]", " => "], ['','', " / <span style='color: #0060df'>", "</span>", ": "], print_r($2d_array, true)), ")"), "/ ")
Upvotes: 0
Reputation: 304
This is what I use:
$width = 150;
$height = 100;
print json_encode(compact('width')) . PHP_EOL;
print json_encode(compact('height')) . PHP_EOL;
The output is:
{"width":369}
{"height":245}
The added benefit is that you can do multiple variables into the compact function at once:
print json_encode(compact(['width', 'height'])) . PHP_EOL;
The output in this case is:
{"width":369,"height":245}
Upvotes: 0
Reputation: 6631
Note that it is possible to replace several different chars (for example line break and null) at the same time, e.g.:
echo str_replace(array("\n", "\0"), "", print_r($product_array, 1))
Upvotes: 0
Reputation: 47966
If you're just looking to view the contents of the array for monitoring or debugging purposes, perhaps encoding the array as a JSON would be useful:
print "Print the product_array = " . json_encode($product_array);
Result:
Print the product_array = {"id":1,"description":"phones","type":"iphone"}
Alternatively, you could use the var_export
function to get a parsable representation of the variable and then simply remove all the new line characters in the string.
var_export
— Outputs or returns a parsable string representation of a variable
Here is a simple example:
$str = var_export($product_array, true);
print "Print the product_array = " . str_replace(PHP_EOL, '', $str);
This will give you exactly the result you specified:
Print the product_array = array ( 'id' => 1, 'description' => 'phones', 'type' => 'iphone',)
I would recommend the first option since it requires less "manipulation" of the strings - the second option starts to perform replacements where as the first simply provides a readable output right away.
Upvotes: 10
Reputation: 1993
$arrayString = print_r($array, true);
echo str_replace("\n", "", $arrayString);
The second value of print_r lets the function return the value instead of printing it out directly.
Upvotes: 5