Add to Favorites

PHP script - list to php array

Save yourself some formatting work when making arrays from lists, make php write the code for you.

Lets say you found yourself a list of states ( list below shortened for brevity ) and you want to turn that list into a php array. You don't want to go in by hand and format this array one item line at a time. Here is some code that will help you with this.

$text = <<< ENDTEXT
Alabama
Alaska
Arizona
Arkansas
California
Colorado
Connecticut
Delaware
District of Columbia
Florida
ENDTEXT;

$arr = array();
$lines = explode("\n",$text);
foreach($lines as $l) {
$str = trim($l);
if ( ! $str ) continue;
array_push($arr,$str);
}

var_export($arr);

After you run this code, you will see it has outputted valid php code for your array. If you want a more concise array ( without the array defining the numerical index for each item ) you can change the code to the following and it will generate it for you.

$text = <<< ENDTEXT
Alabama
Alaska
Arizona
Arkansas
California
Colorado
Connecticut
Delaware
District of Columbia
Florida
ENDTEXT;

echo "array(\n";
$lines = explode("\n",$text);
foreach($lines as $l) {
$str = trim($l);
if ( ! $str ) continue;
echo "\t'$str',\n";
}
echo ")";

That's all there is too it, you now have a php script writing php for you.

Comments

Be the first to leave a comment on this post.

Leave a comment

To leave a comment, please log in / sign up