How to echo values from unique_array? - php

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

Related

PHP prevent html entity creation at string concatenation

How can i prevent that PHP converts a recognized part of a string to an html-entity?
So e.g. lets say i have to concat parts together to an url, like:
echo '&' . 'section=' . '<br>';
$a = '&a';
$b = 'mplitude=';
echo "{$a}{$b}" . '<br>';
echo sprintf("%s%s", '&quote', '=');
the code above prints the following:
§ion=
&litude=
"e=
instead of:
&section=
&amplitude=
&quote=
how can this be prevented without throwing filters on it trying to convert the symbols back to an string again?
You need using htmlspecialchars function:
echo htmlspecialchars('&' . 'section=' . '<br>');

Weird issue with concatenate variables

I am a weird issue regarding my class property here
I have the following:
$this->tableData = '<table>';
$this->tableData .= $string;
echo $this->tableData => output <table>
I want to concatenate more string to my $this->tableData but it seems like nothing is added.
I know $string is not null and contains characters
Did I do something wrong here?
Thanks!
To see if your string is not null you should use var_dump() or print_r() functions.
Example:
$this->tableData = '<table>';
echo "Dumping tableData: " . var_dump($this->tableData);
$this->tableData .= $string;
echo "Dumping tableData 2: " . var_dump($this->tableData);
echo "Dumping string: " . var_dump($string);
That way you will see exactly what is going on.
Is your variable $string containing a HTML tag, something like <p></p> or else ?
This could be "hidden" if you print_r it inside a browser.

Syntax and Variables in PHP

I'm having some trouble with writing some syntax. I want to echo this
'location_1' => $location_1,
However, it is not as simple as it seems. When I write the echo statement the integer 1 must be the variable $z. Here is the code I attempted to write
echo "'location_' . $z . '' =>' . ${'location_' . $z} . ','";
This is what it outputted
'location_' . 1 . '' =>' . something . ','
$location_1 is equal to the string something. I'm lost at how to do this the right way. Any guides on describing how this syntax works would be a major help too so I can understand it completely.
You can just write variables directly into double quoted strings see http://www.php.net/manual/en/language.types.string.php#language.types.string.parsing
echo "'location_$z' => \$location_$z,";
You might want to also read the rest of the strings doc
This is the link to the echo documentation (see the examples, I think they described well how it works)
You can break it into two lines and get the expected output.
For example:
$var_location = "$". "location". $z;
echo "'location_" . $z . "' =>'" . $var_location . "','";
One way is: echo "'location_{$z}' => \$location_{$z},";
Edit: Is this what you meant?
<?php
$z = 1;
$location_1 = 'something';
echo "'location_$z' => " . ${'location_'. $z} . ',';
which produces: 'location_1' => something,
Why don't you store these variables inside an array for easier access. Something like:
$locations = array('location_id' => 'location_name');
Here's one way:
echo "'location_$z' => \$location_$z,";
You need to escape the $ symbol. The double quotes represent the thing to echo in this case, whereas the single quotes actually get echoed.

printing a php variable as it is : with all the special characters

Ok I need to find out what is contained inside a PHP variable and I have it to do it visually, is there a function to display whatever that's contained in a string as it is?
For example :
$TEST = '&nbsp' . "\n" . ' ';
if I use echo the output will be :
while i want it to be :
&nbsp\n&nbsp
is it possible? (I hope I was clear enough)
ty
You can use json_encode with htmlspecialchars:
$TEST = ' ' . "\n" . ' ';
echo json_encode(htmlspecialchars($TEST));
Note that json_encode has third agrument in PHP 5.4.
var_dump() should do the work for you?
Example:
echo "<pre>";
var_dump($variable);
echo "</pre>";
Use <pre> to keep the format structure, makes it alot easier to read.
Resources:
http://php.net/manual/en/function.var-dump.php
http://www.w3schools.com/tags/tag_pre.asp
Try print_r, var_dump or var_export functions, you'll find them very handy for this kind of needs!
http://www.php.net/manual/en/function.htmlspecialchars.php
or
http://www.php.net/manual/en/function.htmlentities.php
$TEST = '&nbsp' . "\n" . ' ';
echo htmlspecialchars(str_replace('\n','\\n', $TEST), ENT_QUOTES);
or
$TEST = '&nbsp' . "\n" . ' ';
echo htmlentities(str_replace('\n','\\n',$TEST), ENT_QUOTES);
You may have to encode the newlines manually. If you want to encode them as actual newlines you can use nl2br. Or string replace these characters with your preference. Update: as I have added to the code per request. String replace special characters you wish to see like newlines and tabs.
assuming you want it for the debugging purposes, let me suggest to use urlencode(). I am using it to make sure I don't miss any invisible character.
The output is not that clear but it works for me.

How to echo with PHP this MySQL command

The following code gives me the following:
$getexpenses = "SELECT sum(expense_amount) FROM projects_expense WHERE project_id=$project_id";
$showexpenses = #mysqli_query ($dbc, $getexpenses); // Run the query.
echo ' . $showexpenses . ';
Gives me a result of
' . $showexpenses . '
instead of the actual sum...
I'm sure it's something simple I'm missing... thanks!
echo " . $showexpenses . " will work for you. You need double quotes, not single.
I added a call to mysqli_fetch_assoc($showexpenses)to make it fully functional.
I also sanitized $project_id to avoid injections and used an alias to make the sum accessible through an associative array.
$getexpenses = "SELECT SUM(`expense_amount`) as `sum_amount` FROM `projects_expense` WHERE `project_id`= ".intval($project_id);
$showexpenses = mysqli_query ($dbc, $getexpenses);
$sums = mysqli_fetch_assoc($showexpenses);
$sum = $sums['sum_amount'];
echo $sum;
We could also have used mysqli_fetch_row like this:
$getexpenses = "SELECT SUM(`expense_amount`) FROM `projects_expense` WHERE `project_id`= ".intval($project_id);
$showexpenses = mysqli_query ($dbc, $getexpenses);
$sums = mysqli_fetch_row($showexpenses);
$sum = $sums[0];
echo $sum;
The alias is not needed anymore since we know the first column (0) is a match.
NB: you probably also need to GROUP BY project_id if you want to use SUM()
use
echo $showexpenses;
or
echo "My query is: {$showexpenses}";
Further to Nik's response, PHP treats strings differently based on whether you use Single Quotes or Double Quotes around them.
Single-Quotes interpret text as literal text except for '\'' which would output a single quote mark and '\' which would output a slash mark. For this reason, using single quotes would output your variable name instead of the value.
Examples:
CODE | OUTPUT
-----------------+------------------
echo '\t'; | \t
echo '\r'; | \r
echo '$foo'; | $foo
Double-Quotes interpret certain escape sequences for special characters and also interpret variables. For instance, "\n" ouputs a linefeed and "\r" outputs a carriage return. For this reason, echoing "$myvariable" outputs the value instead of the variable name.
Examples:
CODE | OUTPUT
-----------------+------------------
echo "\t"; | {tab space}
echo "\r"; | {carriage return}
echo "$foo"; | bar
More reading: http://www.php.net/manual/en/language.types.string.php

Categories