Question

I have a PHP function that in echoing out a string, is losing some of the characters passed in it. Any reason why this would be happening?

I pass: $vhkvdov#jqlydk#p*_L#1qrlws|ufqh#KWLZ#1hwdgsX

It returns: #jqlydk#p*_L#1qrlws|ufqh#KWLZ#1hwdgsX

This is my PHP code:

<?php
function display($str) {
    echo $str;
}
display("$vhkvdov#jqlydk#p*_L#1qrlws|ufqh#KWLZ#1hwdgsX");
?>
Was it helpful?

Solution

If you have $ in you string use single quotes:

display('$vhkvdov#jqlydk#p*_L#1qrlws|ufqh#KWLZ#1hwdgsX');

Otherwise PHP would try to use $vhkvdov as a variable name and replace it by its contents, what will be nothing as I expect that the variable is not set

PHP reference on strings


Note: During development I would set error_reporting in php.ini to

error_reporting=E_ALL | E_NOTICE;

and

display_errors=On

or

log_errors=On
error_log=PATH/TO/YOUR/LOG.file ; make sure this is writable by the web server

To see an error message like :

PHP Notice: Undefined variable: vhkvdov in

OTHER TIPS

The problem is that you are using double quotes, which make PHP interpret the inner string for PHP variables.

Consider the following example:

$friend = "foo";
echo "hello $friend";
// Output: hello foo

Use single quotes instead if you do not want PHP to interpret the string contents.

$friend = "foo";
echo 'hello $friend';
// Output: hello $friend

Take a read of this to help clarify why this is happening:

http://php.net/manual/en/language.types.string.php

Specifically:

When a string is specified in double quotes or with heredoc, variables are parsed within it.

This is whats happening with your code:

If a dollar sign ($) is encountered, the parser will greedily take as many tokens as possible to form a valid variable name. Enclose the variable name in curly braces to explicitly specify the end of the name.

Here is an example:

<?php
$juice = "apple";

echo "He drank some $juice juice.".PHP_EOL;
// Invalid. "s" is a valid character for a variable name, but the variable is $juice.
echo "He drank some juice made of $juices.";
?>

The above example will output:

He drank some apple juice.

He drank some juice made of .

When you use single quotes, you will avoid this issue as the string taken litterally:

// Outputs: This will not expand: \n a newline
echo 'This will not expand: \n a newline';

// Outputs: Variables do not $expand $either
echo 'Variables do not $expand $either';
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top