Why differences in output using SUPERGLOBAL in PHP? - php

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.

Related

RSS Feed parse showing error after :

This is a strange one for me, i am parsing an rss feed using simplexml_load_file, it's working fine up until:
<?php
$xml = simplexml_load_file($url);
$items = $xml->channel->item;
foreach($items as $offer)
{
echo $offer->title;
echo "<br />";
echo $offer->guid;
echo "<br />";
echo $offer->description;
echo "<br />";
echo $offer->campinfo:amount;
echo "<br />";
echo $offer->campinfo:country;
echo "<br />";
echo $offer->campinfo:type;
echo "<br />";
echo "<hr>";
?>
It hits these parts:
$offer->campinfo:amount; the ":" is causing the script to error out, Parse error: syntax error, unexpected ':', expecting ',' or ';'
I cannot find any information on this, any help would be appreciated.
EDIT: example added
<item>
<title>win iPhone 6s!</title>
<link>http://qckclk.com/offer.php?id=341201&pub=240627&subid=</link>
<guid>http://qckclk.com/offer.php?id=341201&pub=240627</guid>
<description>il suffit d';entrer votre numéro pour gagner 6s iPhone!</description>
<campinfo:amount>10.24</campinfo:amount>
<campinfo:campid>341201</campinfo:campid>
<campinfo:country>LU</campinfo:country>
<campinfo:type>Pin+Submit</campinfo:type>
<campinfo:epc>1.01</campinfo:epc>
<campinfo:ratio>9</campinfo:ratio>
</item>
: is not valid in a variable name. If you need to access a property that isn't a valid identifier, you need to use {"string"} notation:
echo $offer->{"campinfo:amount"};
http://php.net/manual/en/language.variables.basics.php
A valid variable name starts with a letter or underscore, followed by
any number of letters, numbers, or underscores
As a regular expression, it would be expressed thus:
'[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*'
echo $offer->campinfo:amount;
contains : in the variable, which isnt legal according to the manual.
Change that or var_dump ($offer) to see whats actually in there
For anyone needing to know in future the answer was:
$offer->children('campinfo', true)->amount;

Double quoted nested array won't work

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.

Displaying the number of users online and the page they are browsing

When I open the page it returns :
Parse error: syntax error, unexpected T_VARIABLE, expecting ',' or ';' in /home/a1361025/public_html/9/9/functions.php on line 44
and this is line 44
echo "$count. ($useronline[ip]) Browsing page: $useronline[page]";
Just try with:
echo $count . ' (' . $useronline['ip'] . ') Browsing page: ' . $useronline['page'] . '';
You have to escape your quotation marks, if you dont want them to end your string:
echo "$count. ($useronline[ip]) Browsing page: $useronline[page]";
You end the string and then paste a variable straight afterwards:
echo "$count. ($useronline[ip]) Browsing page: $useronline[page]";
// ^^^^^^^^^^^^^^^^^^^
You need to escape them with a backslash (because you use double quotes inside of double quotes):
echo "$count. ($useronline[ip]) Browsing page: $useronline[page]";
// ^ ^

How to echo values from unique_array?

So I have the following PHP code for a registration form:
<?php
$entries = array(
0 => $_POST['signup_username'],
1 => $_POST['signup_email'],
2 => $_POST['signup_password']);
$entries_unique = array_unique($entries);
$entries_unique_values = array_values($entries_unique);
echo " <br />".$entries_unique_values. " ";
?>
... And I'm realizing my echo syntax is wrong. How could I echo the different values of my array, without assigning a variable to each of my keys (there are a number of reasons as to why I can't do that)? I'd rather not use the r_print function as well.
Thanks in advance!
How do you want to output them? Comma-separated? Each on its own line? You have plenty of options. This should do the trick for comma-separated:
echo " <br />".implode(', ', $entries_unique). " ";
That said, be careful just outputting user input directly in HTML. This will leave you wide open to XSS vulnerabilities and invalid HTML in general. To output user input in HTML safely, you need to properly HTML encode the output. This would be preferable to the line above:
echo " <br />".implode(', ', array_map('htmlspecialchars', $entries_unique)). " ";
See implode(), array_map(), and htmlspecialchars().
Take a look at php's var_export().
var_export — Outputs or returns a parsable string representation of a variable
Try the implode() function:
echo implode(', ', array_values($entries));
he foreach loop is really easy for arrays, especially single associate arrays.
foreach($entries_unique as $key => $value) {
echo "key: " . $key . " - value: " . $value . "<br/>";
}
Check out php.net: http://php.net/manual/en/control-structures.foreach.php

Separate quotes from string

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'.

Categories