Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print an Array on one line

Tags:

arrays

html

php

I've searched for answers but none have related directly or i haven't been able to adapt it to fix my problem

How would I print the following in one line

<?php

$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 )

like image 930
A.Hobbs Avatar asked Nov 15 '15 15:11

A.Hobbs


3 Answers

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.

like image 104
Lix Avatar answered Oct 30 '22 16:10

Lix


$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.

like image 40
jvecsei Avatar answered Oct 30 '22 17:10

jvecsei


echo str_replace("\n", '', print_r($product_array, true));
like image 45
FallDi Avatar answered Oct 30 '22 15:10

FallDi