Skip to content

Instantly share code, notes, and snippets.

@traeH-Heart
Created March 2, 2015 05:49
Show Gist options
  • Select an option

  • Save traeH-Heart/0c9c1cbb25d490bce448 to your computer and use it in GitHub Desktop.

Select an option

Save traeH-Heart/0c9c1cbb25d490bce448 to your computer and use it in GitHub Desktop.
String in different ways
<?php
//STRING IN DIFFERENT WAYS
//----------------------------------------------
echo 'Iam David Heart';
echo 'embedded newlines
embedded newlines
embedded newlines';
echo 'David Heart: "I\'ll be back"';
// Outputs: David Heart: "I'll be back"
echo 'David Heart escape C:\\*.*?';
// Outputs: David Heart escape C:\\*.*?
echo 'David Heart can ou expand: \n a newline';
// Outputs: This will not expand: \n a newline
echo 'David Heart with the variables $david $heart';
// Outputs: David Heart with the variables $david $heart
//----------------------------------------------
$juices = array("apple", "orange", "koolaid1" => "purple");
echo "He drank some $juices[0] juice.".PHP_EOL;
echo "He drank some $juices[1] juice.".PHP_EOL;
echo "He drank some $juices[koolaid1] juice.".PHP_EOL;
class people {
public $david = "david heart";
public $jopper = "jopper bardillas";
public $gian = "gian adrias";
public $abunda = "abunda";
}
$people = new people();
echo "$people->david drank some $juices[0] juice.".PHP_EOL;
echo "$people->david then said hello to $people->jopper.".PHP_EOL;
echo "$people->gian's wife greeted $people->jopper.".PHP_EOL;
echo "$people->jopper greeted the two $people->abunda."; // Won't work
//-------------------------------------------------------------------------
$hello = 'my Hello World';
// Won't work, outputs: This is { my Hello World }
echo "This is { $hello}";
// Works, outputs: This is my Hello World
echo "This is {$hello}";
echo "This is ${hello}";
// Works
echo "This sample is {$square->width}00 centimeters broad.";
// Works, quoted keys only work using the curly brace syntax
echo "This works: {$arr['key']}";
// Works
echo "This works: {$arr[4][3]}";
// This is wrong for the same reason as $foo[bar] is wrong outside a string.
// In other words, it will still work, but only because PHP first looks for a
// constant named foo; an error of level E_NOTICE (undefined constant) will be
// thrown.
echo "This is wrong: {$arr[foo][3]}";
// Works. When using multi-dimensional arrays, always use braces around arrays
// when inside of strings
echo "This works: {$arr['foo'][3]}";
// Works.
echo "This works: " . $arr['foo'][3];
echo "This works too: {$obj->values[3]->name}";
echo "This is the value of the var named $name: {${$name}}";
echo "This is the value of the var named by the return value of getName(): {${getName()}}";
echo "This is the value of the var named by the return value of \$object->getName(): {${$object->getName()}}";
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment