0

Is it possible to generate variable names from array or list to avoid repetition? I am pulling item values from html form, this is the excerpt of code:

    $item1 = $item2 = $item3 = $item4 = "";


    if (isset($_GET["submit"])) {

        if (!empty($_GET["item1"])) { $item1 = htmlentities($_GET["item1"]);} else { $item1="*"; }
        if (!empty($_GET["item2"])) { $item2 = htmlentities($_GET["item2"]);} else { $item2="*"; } 
        if (!empty($_GET["item3"])) { $item3 = htmlentities($_GET["item3"]);} else { $item3="*"; } 
        if (!empty($_GET["item4"])) { $item4 = htmlentities($_GET["item4"]);} else { $item4="*"; } 

    }

Would it be possible to make array of items and generate the if block with foreach ?

1
  • Use arrays. Much easier to iterate. Commented Mar 21, 2017 at 14:17

2 Answers 2

1

Consider saving the values in an array

For the whole $_GET

$items = [];  
foreach($_GET as $key=>$val) {
    $items[$val] = !empty($val) ? htmlentities($val) : '*';
}

print_r($items);

For some predefined elements in $elements

$items = []; 
$elements = array('item1','item2');

foreach($elements as $val) {
    $items[$val] = !empty($_GET[$val]) ? htmlentities($_GET[$val]) : '*';
}

print_r($items);
Sign up to request clarification or add additional context in comments.

2 Comments

That's it! Thank you very much!
You're welcome. Don't forget to upvote and mark it as answer ;)
0

something like this?

$names = array('item1', 'item2','item3','item4');

foreach($names as $name)
{
    $$name = '';
    if (isset($_GET['submit']))
        $$name = empty($_GET[$name])?'*':htmlentities($_GET[$name]);

}

Comments

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.