phparraysvariables

how to show two values in a same variable in php


I wanted define two values in a same variable. At first was wrote same this:

<body>
    <a href="name.php?firstname=Tom&amp;lastname=schneider">Hi, I’m Tom schneider!</a>
</body>

and in php:

    <?php
    $name = $_GET['firstname' , 'lastname'];
    echo 'Herzlich Willkommen ' . $name . '!';
    ?>

And I had this error: Parse error: ( ! ) Parse error: syntax error, unexpected token ",", expecting "]" in /websites/default/public/name.php on line 9 next time I seperated the values:

$name = $_GET['firstname']['lastname'];

and thie error: Fatal error: Uncaught TypeError: Cannot access offset of type string on string in /websites/default/public/name.php on line 9 ( ! ) TypeError: Cannot access offset of type string on string in /websites/default/public/name.php on line 9

how can I set the values in a same variables?


Solution

  • If you are always going to receive firstname and lastname, and in this order, you can try the below:

    <?php
    $name = implode(' ', $_GET);
    echo "Herzlich Willkommen {$name}!";
    ?>
    

    implode(' ', $_GET) will join the elements of the $_GET array, which should always have the firstname and lastname properties. Perhaps that is something that will be validated in the frontend.