Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I make this programme format the string properly? PHP – Nested For Loop

<?php
$list = ['a', 'b', 'c']; 
$count = [1, 3, 5];

function stringFormatter($c, $i) {
    return "Char is $c & Int is $i"; 
}

for ($i = 0; i < $list; $i++) {
    for ($j = 0; $j < $count; $j++) {
        $string = stringFormatter($list[$i], $count[$j]);
        print $string;
    }
}
?>

This is sample code that I have rewritten to demonstrate an issue I’m having with a program where I want to assign a formatted string, with the right combination of char and int, to be able to execute an SQL statement, using said string. Ideal scenario is getting a string that has the combination of both char and int at that position in their respective lists. E.g. "Char is a & Int is 1". This doesn’t currently compile and when I plug it into "Online PHP Sandbox" I get the error message: "Internal Server Error [500]." Any advice on how I could get this to work, or even alternative suggestions are welcome! Thanks in advance!

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

for ($i = 0; i < $list; $i++) {
for ($j = 0; $j < $count; $j++) {

There are a few syntax errors here – watch out for a missing $ (look at the i inside the outer loop). You probably mean something like $i<count($list) using the built in count function. Similarly in the inner loop you are referencing the $count array with $j<$count – do you mean $j<count($count) or are you using the outer array as in index for the inner element i.e. $j < $count[$i].

On a more general note there are a collection of functions built into php to better handle passing of values into mysql (etc) – you should probably be looking at using those – search on "sanitising" with php and mysqli.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading