Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing PHP Array into a string with correct syntax

Tags:

If I have this array:

<?php 

$myarray =  Array
                (
                        'keyword' => 'seo',
                        'title_factor' => false,
                        'description_factor' => false,
                        'headtags_factor' => false,
                        'imgalt_factor' => false,
                        'keyword_density' => 0,
                );


var_dump($myarray);
print_r($myarray);                      


?>

Here is the output of vardump and print_r:

array(6) {
  ["keyword"]=>
  string(3) "seo"
  ["title_factor"]=>
  bool(false)
  ["description_factor"]=>
  bool(false)
  ["headtags_factor"]=>
  bool(false)
  ["imgalt_factor"]=>
  bool(false)
  ["keyword_density"]=>
  int(0)
}
Array
(
    [keyword] => 'seo'
    [title_factor] => 
    [description_factor] => 
    [headtags_factor] => 
    [imgalt_factor] => 
    [keyword_density] => 0
)

Here is what I want as output:

    "Array
    (
            'keyword' => 'seo',
            'title_factor' => false,
            'description_factor' => false,
            'headtags_factor' => false,
            'imgalt_factor' => false,
            'keyword_density' => 0,
    );"    
like image 559
Aivan Monceller Avatar asked Sep 06 '11 08:09

Aivan Monceller


People also ask

Which PHP code is correct to print array?

We can use var_dump() or print_r() to display the values of an array in human-readable format or to see the output value of the program array.

What is the syntax of array in PHP?

Syntax for indexed arrays: array(value1, value2, value3, etc.) Syntax for associative arrays: array(key=>value,key=>value,key=>value,etc.)


2 Answers

Use var_export()[docs]:

$string = var_export($array, true);
like image 76
Arnaud Le Blanc Avatar answered Oct 14 '22 18:10

Arnaud Le Blanc


You're searching for var_export if I'm correct

more info about var_export at http://www.php.net/manual/en/function.var-export.php

like image 41
Tom Vervoort Avatar answered Oct 14 '22 16:10

Tom Vervoort