Search code examples
phpstringsyntaxconstantseol

Which is the correct way of using core predefined constant PHP_EOL inside a double quoted string and single quoted string?


Consider below code example making use of PHP_EOL :

<?php

  $juices = array("apple", "orange", "koolaid1" => "purple");
  class people {
    public $john = "John Smith";
  }

  $string = 'string';
  $people = new people();

  //In below statement dot(.) is used before PHP_EOL
  echo "$people->john drank some $juices[0] juice.".PHP_EOL;

  //In below statement comma(,) is used before PHP_EOL
  echo "The character at index -2 is $string[-2].", PHP_EOL;

?>

Output :

John Smith drank some apple juice. 
The character at index -2 is n. 

If you look at the above code closely, especially at the lines making use of PHP_EOL, you will come to know the difference in the preceding character to PHP_EOL in both statements.

In first statement PHP_EOL is preceded by a dot(.) whereas in second statement it is preceded by a comma(,)

Why such difference is there in the syntax as both the statements are generating the same output only?

Someone please clear the confusion.

Note : I know that core predefined constant PHP_EOL is used to put the correct 'End Of Line' symbol for the platform on which program is executing.


Solution

  • echo "$people->john drank some $juices[0] juice.".PHP_EOL;
    

    Here .(dot) works like it will first concatenate the total string then prints.

    But comes to ,

    echo "The character at index -2 is $string[-2].", PHP_EOL;
    

    it won't concatenate. it will print one after other based on ,