0

I have a list of strings I need to convert into an array assignment

eg lets say I have a set of lines like this:

   ctools_export_ui_list_form
   masquerade_block_1
   switchtheme_switch_form
   backup_migrate_ui_manual_backup_load_profile_form
   backup_migrate_ui_manual_backup_form

I need to create a variable assignment like this:

$conf['journal_form_ids'] = array(
   'ctools_export_ui_list_form' => 0,
   'masquerade_block_1' => 0,
   'switchtheme_switch_form' => 0,
   'backup_migrate_ui_manual_backup_load_profile_form' => 0,
   'backup_migrate_ui_manual_backup_form' => 0,
);

My idea is to use some HEREDOC syntax:

 $str = <<<EOD
 ctools_export_ui_list_form
 masquerade_block_1
 switchtheme_switch_form
 backup_migrate_ui_manual_backup_load_profile_form
 backup_migrate_ui_manual_backup_form
EOD

and use that to create the variable assignment text and eval it, or some other suitable method.

Are there built in routines to make it elegant?

0

1 Answer 1

2

not sure what HEREDOC really has to do with anything, here is my commented version:

<?php


$foo="ctools_export_ui_list_form
   masquerade_block_1
   switchtheme_switch_form
   backup_migrate_ui_manual_backup_load_profile_form
   backup_migrate_ui_manual_backup_form";

//make the array
$x=explode(PHP_EOL,$foo);
//swap the keys and values
$x=array_flip($x);
//set the value of all to 1
$x = array_fill_keys(array_keys($x), 1);
print_r($x);
Sign up to request clarification or add additional context in comments.

5 Comments

The HEREDOC is for tidiness. I am copying and pasting the lines from a long text list in the PHP block and I want to avoid any formatting errors.
$foo can be any string structure you like - same result
To wit, you would use the HEREDOC to establish the value of $foo then the rest still applies. Still though this looks like configuration so what dont you just parse a configuration file like INI or JSON?
@Dagon Thanks for a neat answer. It saved me a lot of inelegant code to construct a string for an eval
can't imagine where eval() would come in to it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.