Skip to content

Instantly share code, notes, and snippets.

@daveh
Last active November 13, 2019 11:18
Show Gist options
  • Save daveh/ae09c5aa6bbce500076087312233ca31 to your computer and use it in GitHub Desktop.
Save daveh/ae09c5aa6bbce500076087312233ca31 to your computer and use it in GitHub Desktop.
Concatenating strings in PHP (https://youtu.be/sOmHCk-_UaM)
// Code to accompany this video: https://youtu.be/sOmHCk-_UaM
// 1. The concatenation operator
$message = "Hello " . "world"; // $message contains "Hello world"
// 2. The concatenating assignment operator
$title = "Home";
$title .= " | About"; // $title now contains "Home | About"
// 3. Splitting concatenations onto more than one line
$seasons = "Spring" . "Summer" . "Autumn" . "Winter";
$seasons = "Spring"
. "Summer"
. "Autumn"
. "Winter";
// 4. Putting a space either side of the operator:
$sql = "SELECT id FROM " . $table_name;
// 5. Simple variable interpolation
$name = "Dave";
$message = "Hello $name!"; // $message contains "Hello Dave!"
// 6. Variable interpolation with curly braces
$prefix = "wp_";
$sql = "INSERT INTO {$prefix}user"; // $sql contains "INSERT INTO wp_user"
// 7. The sprintf function
$temp = 20;
$city = 'Paris';
echo sprintf("It's %d° in %s", $temp, $city); // outputs "It's 20° in Paris"
// 8. Joining an array of strings with a loop
$categories = ['news', 'tech', 'humour'];
$text = '';
foreach ($categories as $category) {
$text .= $category . ',';
}
// $text contains "news,tech,humour,"
// 9. Joining an array with the implode function
$categories = ['news', 'tech', 'humour'];
$text = implode(',', $categories);
// $text contains "news,tech,humour"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment