简体   繁体   中英

what's wrong with my php codes?

I wanted to convert my Javascript code for creating a triangle to PHP codes, the Javascript codes works but the PHP code doesn't. This is what I have in my PHP codes, I tried to run it but ended up with a fatal error and undefined variable. I understand javascript but not php...

<?php 
    {
        $size = $_POST['size'];
        $firstChoice = $_POST['firstChoice'];
        $secondChoice = $_POST['secondChoice'];

         echo "<textarea>";
            $allLines = '';
                for ( $i = 1; $i <= $size; $i++ ) 
                    {
                    $oneLine = createLine ( $i, $i % 2 ? $FirstChoice : $secondChoice );
                    $allLines += $oneLine + "\n";
                    }
            echo "$allLines";

             function createLine ($size, $symbol) {
             $aLine = '';
                for ( $j = 1; $j <= $size; $j++ )
                {
                    echo $aLine += $symbol;
                }
                echo "$aLine";
            echo "</textarea>";         
    }
?>

It should look like this if size = 5 , firstChoice = # and secondChoice = &

#
&&
###
&&&&
#####

What is $createLine ? Looks as if you're trying to use it as a function, but it is not defined anywhere.

Edit :

You need to declare the function in php

function createLine($size, $symbol) {
  // code
}

And when you call it, just call it by the name, don't add a $ .

$line = createLine($a, $b);

See documentation on php User-defined functions .

Working :

There were a few issues including: string concatenation should be using the . operator not + , a typo in $FirstChoice , and the function needs to be defined before you use it.

<?php
  $size = $_POST['size'];
  $firstChoice = $_POST['firstChoice'];
  $secondChoice = $_POST['secondChoice'];

  function createLine($size, $symbol) {
    $aLine = '';
    for ($j = 1; $j <= $size; $j++) {
      $aLine .= $symbol;
    }
    return $aLine;
  }

  echo "<textarea>";
  $allLines = '';
  for ($i = 1; $i <= $size; $i++) {
    $oneLine = createLine($i, $i % 2 ? $firstChoice : $secondChoice);
    $allLines .= $oneLine . "\n";
  }
  echo "$allLines";
  echo "</textarea>";
?>

Use createLine(...) and not $createLine(...) I suppose you have javascript function like below

<script>
function createLine (...)
{
...
}
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM