variables in echo or print

Discussion in 'PHP' started by mnymkr, Aug 5, 2007.

  1. #1
    when or when do you not have to use a '. to call varialbe in echo or print

    i have seen this


    echo "hey hi heya".$var." bah ";

    as well as

    print "hey hi heya $var bah";

    when do you have to quote period and when not
     
    mnymkr, Aug 5, 2007 IP
  2. bilal@revolutionhosting

    bilal@revolutionhosting Peon

    Messages:
    32
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #2
    With just regular variables in double-quoted strings, there's not really any context where you need to use the concatenation operator ".".

    You do, however, need to concatenate "." when calling functions, doing arithmetic, etc, and always in single-quotes.

    For example:
    
    // All of the following work
    // For better readability, you may want to try wrapping your variables in brackets {}
    // Regular variable
    print "Hello, $name";
    print "Hello, {$name}";
    print "Hello, " . $name;
    
    // Array variable
    print "Hello, $person['name']";
    print "Hello, {$person['name']}";
    print "Hello, " . $person['name'];
    
    // Object variable
    print "Hello, $person->name";
    print "Hello, {$person->name}";
    print "Hello, " . $person->name;
    
    // This does not work, because it is a single-quoted string
    print 'Hello, $person';
    // So you should use the concatenation operator in this case
    print 'Hello, ' . $person;
    
    // This also does not work, because you're calling a function
    print "Hello, function()";
    // So concatenate in this case as well
    print "Hello, " . function();
    
    PHP:
    The ability to replace variables in strings is definitely a very useful convenience feature of PHP.

    For more detailed information, you should consult the following page (specifically the variable parsing section):
    http://us3.php.net/manual/en/language.types.string.php
     
  3. exodus

    exodus Well-Known Member

    Messages:
    1,900
    Likes Received:
    35
    Best Answers:
    0
    Trophy Points:
    165
    #3
    Be careful. Single Quote and Double Quoes mean a different thing. You were asking when so you use '. , but then you ask about ". Single does not phrase the variables and a Double parases the variables.
     
    exodus, Aug 6, 2007 IP
  4. olaf2

    olaf2 Active Member

    Messages:
    1,362
    Likes Received:
    10
    Best Answers:
    0
    Trophy Points:
    80
    #4
    use single quotes for strings since they are much faster
     
    olaf2, Aug 7, 2007 IP