search

Home  >  Q&A  >  body text

How can I make this program format the string correctly? PHP - Nested For Loops

<?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 a sample code I rewrote to demonstrate a problem I'm having in a program where I want to allocate a formatted string using the correct combination of char and int to be able to execute a SQL statement , using say string. The ideal situation is to get a string that has a combination of both char and int at that position in their respective lists. For example. "Char is a and Int is 1". It currently doesn't compile and when I plug it into the "Online PHP Sandbox" I get the error: "Internal Server Error [500]". Any suggestions on how to make it work or even other suggestions are welcome! Thanks in advance!

P粉006540600P粉006540600390 days ago750

reply all(2)I'll reply

  • 定静安断明悟空

    定静安断明悟空2024-02-01 17:37:10

    <?php
    $list = ['a', 'b', 'c'];
     $count = [1, 3, 5]; 
     function stringFormatter($c, $i) {  
       return "Char is $c & Int is $i"; } 
       for ($i = 0; i < count($list); $i++) {  
              $string = stringFormatter($list[$i], $count[$i]);   
                  print $string; 
    }?>

    Hope it helps you

    reply
    0
  • P粉677684876

    P粉6776848762024-01-18 00:39:00

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

    There are some syntax errors here - note the missing $ (look at the i inside the outer loop). You're probably referring to $i using the built-in counting function

    More generally, there is a set of functions built into php that handle passing values ​​into mysql (etc.) better - you should probably consider using these - search for "clean" using php and mysqli.

    reply
    0
  • Cancelreply