php - Create Associative Array using For Loop

I want an array in the below format using Variables stored from the database and $_GET
array('FNAME' => 'NIDHI','EMAIL' => '[email protected]','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) "[email protected]" } [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) "" } }
Answer
Solution:
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>';
Answer
Solution:
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>");
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: xml parsing error: no root element found
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.