note 119533 added to book.array

From: Date: Fri, 01 Jul 2016 12:53:30 +0000
Subject: note 119533 added to book.array
Groups: php.notes 
Request: Send a blank email to php-notes+get-205851@lists.php.net to get a copy of this message
If you want to generate a PHP file that returns an array from an array that you read, you will need to parse array, because print_r() function does not generate correct syntax. Function below generate valid content for a new multidimensional array from a previous array and allow you to indent text. <?php function arrayToPrint($array, $tabs = 1) { $text = ''; foreach($array as $index => $value){ if (is_array($value)){ $text .= str_repeat("\t",$tabs) . "'$index' => array(\n" . str_repeat("\t",$tabs) . arrayToPrint($value, $tabs + 1) . "\n" . str_repeat("\t",$tabs) . "),\n"; } else { $value = is_string($value) ? "'$value'" : $value; $value = is_bool($value) ? ($value ? 'TRUE' : 'FALSE') : $value; $text .= str_repeat("\t",$tabs) . "'$index' => $value,\n"; } } return $text; } ?> You can generate a file that returns an array so: <?php $text = "<?php return array(\n" . arrayToPrint($previousArray) . "\n);"; file_put_contents($file,$text); ?> $previousArray is an array variable with content. ---- Server IP: 72.52.91.14 Probable Submitter: 200.198.222.64 ---- Manual Page -- http://php.net/manual/en/book.array.php Edit -- https://master.php.net/note/edit/119533 Del: integrated -- https://master.php.net/note/delete/119533/integrated Del: useless -- https://master.php.net/note/delete/119533/useless Del: bad code -- https://master.php.net/note/delete/119533/bad+code Del: spam -- https://master.php.net/note/delete/119533/spam Del: non-english -- https://master.php.net/note/delete/119533/non-english Del: in docs -- https://master.php.net/note/delete/119533/in+docs Del: other reasons-- https://master.php.net/note/delete/119533 Reject -- https://master.php.net/note/reject/119533 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#205851) next »