Consider this :
$a = 'u';
$b[$a] = 'v';
$c[$b[$a]] = 'w';
This works fine:
php > echo $c[$b[$a]];
w
This also works:
php > echo '$c[$b[$a]]';
'$c[$b[$a]]'
However this leads to a syntax error:
php > echo "$c[$b[$a]]";
PHP Parse error: syntax error, unexpected '[', expecting ']'
While a shorter version works:
php > echo "$b[$a]";
v
Why?
In a double quoted string there are two kinds of variable parsing, simple and complex. Simple parsing will only work with a single dimensional array or object. So these will work:
echo "Valid: $foo[1]";
echo "Valid: $foo[bar]";
echo "Valid: $foo->bar";
But these will not:
echo "Invalid: $foo[1][2]";
echo "Invalid: $foo->bar->baz";
echo "Invalid: $foo->bar()[2]";
Complex parsing is what halfer suggested in his answer, which wraps the expression in curly braces, and will indeed solve your problem:
echo "Valid: ${foo[1][2]}";
echo "Valid: ${foo->bar->baz}";
echo "Valid: ${foo->bar()[2]}";
The short answer is: don't write PHP like this! If it is confusing to read then use an intermediate variable.
However, it can be fixed: it looks like PHP just wants the brace delimiters at the outermost edges of the variable:
<?php
$a = 'u';
$b[$a] = 'v';
$c[$b[$a]] = 'w';
echo "{$c[$b[$a]]}";
This is also fine as well:
echo "${c[$b[$a]]}";
In the first case, the whole thing is wrapped in braces, and in the second, the $ is allowed outside of the brace construct to say that the next bit is a variable.
Related
I am getting error by running following code:
<?php
//superglobal.php
foreach($_SERVER as $var=>$value)
{
echo $var=>$value.'<br />'; //this will result in to following error:
//Parse error: syntax error, unexpected '=>' (T_DOUBLE_ARROW), expecting ',' or ';' in
//C:\xampp\htdocs\w_j_gilmore\CH_03_PHP_BASICS\superglobal.php on line 6
}
?>
And following code runs successfully
<?php
//superglobal.php
foreach($_SERVER as $var=>$value)
{
echo "$var=>$value<br />";
}
?>
Printing in single quotation and double quotation is difference.
WHY?
The difference between the 2 is that in the first you are trying to use the => operator (which is not valid in that place, so will result in a syntax error), while in the second you print a string which happens to have the characters = and > in it.
The second effectively could be rewritten as:
<?php
//superglobal.php
foreach($_SERVER as $var=>$value)
{
echo $var . "=>" . $value . "<br />";
}
?>
If you are just trying to output $_SERVER for debug reasons, I suggest using var_dump or print_r
var_dump($_SERVER);
You have not quoted the string:
echo $var=>$value.'<br />';
quoted would look like this:
echo '$var => $value <br />';
if single quoted, variables are not interpreted.
Okay I have been having a little issue with the code below right now it pulls a bunch of data about a few stocks for me but I cant seem to get ride of the [ or ]. I thought it would be easy to remove the brackets by adding them to the end and the beginning of the preg_split but right when I do it just pops a error message.
Is there any command to remove all [ or all ] cause I know I have found a command in the past to remove all non numeric characters thank you so much btw
<?php
$Bloomberg = 'http://www.bloomberg.com/quote/AAPL:US';
$Bloomberghtml = file_get_contents($Bloomberg);
$BloombergStart = preg_split('/data_values":/',$Bloomberghtml);
$BloombergRawData = preg_split('/>/',$BloombergStart[1]);
$OpenTimeStart = preg_split('/exch_open_time":/',$BloombergRawData[0]);
$OpenTime = preg_split('/,"/',$OpenTimeStart[1]);
$CloseTimeStart = preg_split('/exch_close_time":/',$BloombergRawData[0]);
$CloseTime = preg_split('/,"/',$CloseTimeStart[1]);
$StartPriceData = preg_split('/,/',$BloombergRawData[0]);
echo $BloombergRawData[0];
echo "<br><br><br>";
echo $OpenTime[0];
echo "<br>";
echo $CloseTime[0];
echo "<br>";
print_r($StartPriceData);
?>
I'm not sure I fully understood your problem, but if you need to remove the '[' and ']' chars you can do that rather simply:
str_replace(array( '[', ']' ), '', $BloombergRawData);
Not the most elegant solution, but it should to the trick.
I'm trying to build a string of HTML as follows:
$html= "<input name='".GROUP_CONFIG_MAX_CALL_RECORDING_TIME_INPUT."' value='".$MaxCallRecordingTimeSecs."' size='4' ".($bCallRecordingLicensed)?'':'disabled'.">";
But it just gives me a parse error (no specific detail, just that this line is the problem).
I've tried various positioning of quotations and brackets but I'm always getting the parse error. Is this possible the way I'm trying?
$html= "<input name='".GROUP_CONFIG_MAX_CALL_RECORDING_TIME_INPUT."' value='".$MaxCallRecordingTimeSecs."' size='4' ".($bCallRecordingLicensed?'':'disabled').">";
Like codingbiz said, this should work with additional parentheses. I'd go for a more readable version with sprintf though:
$html = sprintf(
'<input name="%s" value="%s" size="4"%s>',
GROUP_CONFIG_MAX_CALL_RECORDING_TIME_INPUT,
$MaxCallRecordingTimeSecs,
( $bCallRecordingLicenced ? '' : ' disabled' )
);
Try
".(($bCallRecordingLicensed)?'':'disabled').">";
additional brackets
Try wrapping the whole ternary in parens, rather than just the variable at the start:
$html= "<input name='".GROUP_CONFIG_MAX_CALL_RECORDING_TIME_INPUT."' value='".$MaxCallRecordingTimeSecs."' size='4' ".($bCallRecordingLicensed?'':'disabled').">";
I think its because you change quote marks:
For example
$test = false;
$strings = "hello ".($test?"you":"")." this is a test";
echo $strings;
works as you expected.
I did find that without the brackets round the test, for example, my test only produced the word "you" .. rather than the whole string - which was odd.
I would like to know what the advantage of using
curly braces is in the following context:
$world["foo"] = "Foo World!";
echo "Hello, {$world["foo"]}.\n";
is over the following:
$world["foo"] = "Foo World!";
echo "Hello, $world["foo"].\n";
In particular, how is it that the braces resolve any
possible ambiguity in this case (or similar cases)?
Second example will not be parsed. So first is better:)
Anyway, I prefer to use
echo "Hello" . $world["foo"] . ".\n";
Because it is more easy to read to me.
Besides, there is another way:
$world["foo"] = "Foo World!";
echo "Hello, $world[foo].\n";
There no resaons to use one or another. you what you(or your team) like.
See the other answers for the "echo" explanation, but if you're using heredoc, such as the following:
echo <<<EOHTML
<td>{$entity['name']}</td>
EOHTML;
You need the curly braces to properly use the associative array.
The following code keeps giving me this error
Parse error: syntax error, unexpected T_VARIABLE in ...
?
$query_string = 'this is a test... "this is in quotes" mmm..chicken burgers... yummm...';
preg_match_all("/\".*\"|[^\s]*/", $query_string, $matches);
echo "Matches:";
foreach($matches[0] as $token) {
echo $token . "<br />";
}
it is from this web page
Have you looked at the line referred to in the Error Message you noted?
Have you looked at the lines preceding that line, to ensure that you have ended each line with the semi-colon ";", that you have used the correct operators for joining variables ".", etc.?
This sounds like a simple PHP Syntax error.
I just ran the following code on my XAMPP server with no error messages apparent:
<?php
$query_string = 'this is a test... "this is in quotes" mmm..chicken burgers... yummm...';
preg_match_all("/\".*\"|[^\s]*/", $query_string, $matches);
echo "Matches:";
foreach($matches[0] as $token) {
echo $token . "<br />";
}
As Col. Shrapnel noted, you have hidden dash symbol (173 decimal, Hex 00ad) in your code right before $query_string. Remove that and you'll be much better.
Update: to be exact, you have [comma], [space], [space], [hidden dash], [space], '$query_string'.