Create Associative Array using For Loop

Viewed 128

I want an array in the below format using Variables stored from the database and $_GET

array('FNAME' => 'NIDHI','EMAIL' => 'example@email.com','SRC' => '')

What I am trying is like below

if ($variableResult->num_rows>0) {
            
            while($variable_row = $variableResult->fetch_assoc()) {

              $variableArray[] = $variable_row['variable_name'];
              
            }
            
            $totalVariables = count($variableArray);
            
            
         
            for($i = 0; $i < $totalVariables; $i++) {
              
              $dataArray[] = array($variableArray[$i] => htmlspecialchars($_GET[$variableArray[$i]]));
              
            }

            var_dump($dataArray);
            exit();
            
        }

It's giving me output like below

array(5) { [0]=> array(1) { ["EMAIL"]=> string(17) "nidhi@example.com" } [1]=> array(1) { ["LNAME"]=> string(5) "NIDHI" } [2]=> array(1) { ["THIS_IS_CUSTOM"]=> string(0) "" } [3]=> array(1) { ["THIS_IS_CUSTOM_2"]=> string(0) "" } [4]=> array(1) { ["THIS_IS_CUSTOM_3"]=> string(0) "" } }

2 Answers

You do not need two loops here. 1) while and 2) for. While is enough.

Note: The below code may not perfect. You may need to change it a little bit :)

$variableArray = []; // declare blank array variable first
while($variable_row = $variableResult->fetch_assoc()) { 
   if(!empty($variable_row['variable_name'])){ // check if key presnt
       $varName = $variable_row['variable_name'];
       if(!empty($_GET[$varName])){ // check if valid get variable exist
            $variableArray[$varName] = htmlspecialchars($_GET[$varName]); 
       }
   }  
}
// print it for better visibility
echo '<pre>'; print_r($variableArray); echo '</pre>';

I believe it's giving you the correct result but the formatting is a bit confusing.

Replace:

var_dump($dataArray);

with:

print("<pre>".print_r($dataArray,true)."</pre>");
Related