PHP: Strings

Derek Bridge

Department of Computer Science,
University College Cork

PHP: Strings

Aims:

Initialisation

Class exercise I: what happens?

<body>

    <?php
        $surname = $_GET['surname'];
        
        echo '<p>';
        echo 'Hello ';
        echo $firstname; 
        echo ' ';
        echo $surname;
        echo '</p>';
    ?>
 
</body>

Class exercise II: what happens?

<body>

    <?php
        $firstname = $_GET['firstname'];
        $surname = $_GET['surname'];
        
        echo '<p>';
        echo 'Hello ';
        echo $frstname; 
        echo ' ';
        echo $surname;
        echo '</p>';
    ?>
 
</body>

Class exercise III: what happens?

<body>

    <?php
        $firstname = $_GET['firstname'];
        $surname = $_GET['surname'];
        
        echo '<p>';
        echo 'Hello ';
        echo $firstName; 
        echo ' ';
        echo $surname;
        echo '</p>';
    ?>
 
</body>

Class exercise IV: what happens?

<body>

    <?php
        $firstname = $_GET['firstname'];
        $surname = $_GET['surname'];
        
        echo '<p>';
        echo 'Hello ';
        echo firstname; 
        echo ' ';
        echo $surname;
        echo '</p>';
    ?>
 
</body>

Expressions, operators and operands

String expressions

Class exercise: What is the output from each of the following?

$word1 = 'Happy';
$word2 = 'Christmas';
$laugh = 'Ho';
  1. echo $word1 . $word2;
  2. echo $word1 . ' ' . $word2;
  3. echo $laugh . $laugh . $laugh;
$wishes = $word1 . ' ' . $word2;
$laugh = $laugh . ' ' . $laugh . ' ' . $laugh;
  1. echo $wishes;
  2. echo $laugh;
  3. echo 'Ho ' . $laugh . ' Ho';

What do the variables contain at the end of all this?

Using string concatenation in programs

<body>

    <?php
        $firstname = $_GET['firstname'];
        $surname = $_GET['surname'];
        
        echo '<p>Hello ' . $firstname . ' ' . $surname . '</p>';
    ?>
 
</body>

Single quotes and double quotes

Long or fiddly

Interpolation

Class exercise: What is the output from each of the following?

$answer = 'forty-two';
  1. echo 'The answer is ' . $answer;
  2. echo 'The answer is {$answer}';
  3. echo 'The answer is $answer';
  4. echo "The answer is " . $answer;
  5. echo "The answer is {$answer}";
  6. echo "The answer is $answer";

Which should I use?