declaring a big list of variables [duplicate] - php

This question already has answers here:
Using braces with dynamic variable names in PHP
(9 answers)
Closed 9 years ago.
I have a big list of variables:
$variable_1 = $_POST['variable_1'];
$variable_2 = $_POST['variable_2'];
$variable_3 = $_POST['variable_3'];
$variable_4 = $_POST['variable_4'];
...
..
.
$variable_86 = $_POST['variable_86'];
What would be the best way to declare all of these variables? Should I just declare them all like above, should I put them in an array, can I declare using a loop?

for ($i = 0; $i <= 86; $i++){
if (isset($_POST["variable_$i"]))
${'variable'.$i} = $_POST["variable_$i"];
}
See this question to learn about Dynamic Variable names.
EDIT: Added the isset command. isset() checks whether a variable is already declared or not

You can use any of the following:
foreach($var as $key=>$value) {
echo $value;
}
and/or:
foreach($_POST['var'] as $key=>$value) {
echo $value;
You could use this also, that will iterate through all POST values:
foreach($_POST as $key=>$value) {
echo "$key=$value";
}
Also, assuming $_POST['variable_1'] $_POST['variable_2'] etc.
foreach($_POST as $k => $v) {
if(strpos($k, 'variable_') === 0) {
echo "$k = $v";
}
}

Related

what is the meaning of ${$key} in the code below? [duplicate]

This question already has answers here:
Reference Guide: What does this symbol mean in PHP? (PHP Syntax)
(24 answers)
Closed 6 years ago.
I just need to know what is the meaning of ${$key} in the code. I already searched google but didn't find answers for this code. So please help me understand it ?
<?php
foreach ($_POST as $key => $value) {
$temp = is_array($value) ? $value : trim($value);
if (empty($temp) && in_array($key, $required)) {
$missing[] = $key;
${$key} = '';
} elseif (in_array($key, $expected)) {
${$key} = $temp;
}
}
?>
Let's say, we have given code:
<?php
$a = 'Hello';
$key = 'a';
echo ${$key};
?>
will print:
Hello
What you are doing here is referring to the value which name is stored in another variable.
Using ${} is a way to create dynamic variables, example:
${'a' . 'b'} = 'hello world!';
echo $ab; // hello world!
Read more at official documentation.

What does the ${$} construct mean? [duplicate]

This question already has answers here:
In PHP, what does the ${$ } syntax do?
(3 answers)
Closed 9 years ago.
I am new to PHP so please i am sorry if this question is a noob. I don't know its name so couldn't find it. I read it in this piece of code. What does it mean?
Line 5: ${$key}
<?php
$expected = array( 'carModel', 'year', 'bodyStyle' );
foreach( $expected AS $key ) {
if ( !empty( $_POST[ $key ] ) ) {
${$key} = $_POST[ $key ];
} else {
${$key} = NULL;
}
}
?>
This is the same as $$key and means a var named $key
i.e.
$test = "foo";
is the same as
$a = "test";
$$a = "foo";
It's a variable variable. Please read more here: http://php.net/manual/en/language.variables.variable.php
The notation ${$key} is an alternative writing style to simply $$key which is used for variable variables.
One particular case in which you could use that notation is when you do tricks like this:
$var = 'foo_x';
$key = 'x';
${'foo_' . $x} = 'hello';
echo $foo_x; // hello
Set variable with name $key.
$var = NULL;
$name = 'var';
${$name} = TRUE;
var_dump($var); // TRUE
As well as:
$$name = TRUE;
It is a way to use dynmaic variable names. See here: http://php.net/manual/en/language.variables.variable.php
It allows for the use of complex expressions.
It's called complex (curly) syntax, you can find more information at http://php.net/manual/en/language.types.string.php#language.types.string.parsing.complex

Whitelist function help needed - in_array is not case sensitive for some reason [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
PHP case-insensitive in_array function
I'm making a function to validate input by having an $input variable and a $whitelist variable. Both are strings and the function parses the $whitelist variable and makes it into a character array to use on the string.
For some reason the in_array function is not distinguishing a lowercase letter from an uppercase one (at least I think that's what's happening).
Link to code: http://pastebin.com/eadAV7gg
Why not match against the lowercase value of the letter. If you match it in the if statement, then you don't have to worry about changing the actual $input string:
foreach ($inputArray as $key => $value)
{
foreach ($whitelistArray as $key2 => $value2)
{
if (in_array(strtolower($value), $whitelistArray))
{
//Do nothing, check passed
}
else
{
unset($inputArray[$key]);
}
}
}
A much shorter version of what you have could be accomplished with:
$input = "ATTT";
$whitelist = "abcdefghijklmnopqrstuvwxyz";
$output = '';
for($x=0; $x<strlen($input);$x++){
if(stristr($whitelist,substr(strtolower($input),$x,1))){
$output .= substr($input,$x,1);
}
}
echo $output;
Or to implement as a function:
function whitelist_string($input=''){
$whitelist = "abcdefghijklmnopqrstuvwxyz";
$output = '';
for($x=0; $x<strlen($input);$x++){
if(stristr($whitelist,substr(strtolower($input),$x,1))){
$output .= substr($input,$x,1);
}
}
return $output;
}
echo whitelist_string('ATTT').'<br>';
echo whitelist_string('Hello88 World!').'<br>';

Replace value in array doesn't work

I'm going crazy, spent a couple of hours trying different methods in replace values in arrays, but I can't get it to work.
foreach($potentialMatches as $potentialKey)
{
$searchKeywordQuery = "SELECT keyword, id FROM picture WHERE id='$potentialKey'";
$searchKeywords = mysql_query($searchKeywordQuery) or die(mysql_error());
while ($searchKeyWordsRow = mysql_fetch_array($searchKeywords))
{
$keyword = $searchKeyWordsRow['keyword'];
$pictureKeywordArray[$searchKeyWordsRow['id']]['keywords'] = explode(",", $keyword);
$pictureKeywordArray[$searchKeyWordsRow['id']]['match'] = 4;
}
}
foreach($pictureKeywordArray as $key = > $picValue)
{
foreach($picValue['keywords'] as $key = > $picIdValue)
{
if ($picIdValue == $searchIdKey)
{
echo $picValue['match'];
$picValue['match']++;
echo $picValue['match'];
}
}
}
foreach($pictureKeywordArray as $key = > $picValue)
{
echo $picValue['match'];
}
I'm novice as you can see, When I echo the picValue['match'] in the foreach loop it gives me a correct value after "++". But then below when I call the array again it gives me the value of 4 instead of 5 as intended. Thanks in advance for any help with this.
Cause you work with the item copy in first case try $pictureKeywordArray[$key]['match'] instead of $picValue['match']
In that second foreach you need to call it by reference:
foreach($pictureKeywordArray as $key => &$picValue)
{ //^-- `&` makes it by reference
foreach($picValue['keywords'] as $key => $picIdValue)
{
if ($picIdValue == $searchIdKey)
{
echo $picValue['match'];
$picValue['match']++; //now updates what you want it to update
echo $picValue['match'];
}
}
}
foreach works on a copy of the data. You must use a reference to modify the original:
foreach ($foo as $i => &$f)
{
$f++;
}
unset($f); // important to do this if you ever want to reuse that variable later

Can't change a value inside a php list

I have the following php loop that takes an array that contains a set of arrays. I use this code to convert each array to a list, so I can manipulate the elements better.
This is my code...
while ($i<sizeof($my_array)){
while(list($key,$val) = each($my_array[$i])){
$j = $i+1;
if ($key == "fruit"){
$val = "ananas".$j;
echo $val;
}
}
$i++;
}
When I print the "search" array (print_r($my_array)), the values don't change. I don't understand why this doesn't work as I had expected. Is there a solution to modify the $val without changing the loop structure and logic?
Use foreach with reference:
$i = 0;
foreach ( $my_array as $key => &$val ) {
++$i;
if ($key == "fruit"){
$val = "ananas" . $i;
echo $val;
}
}
$val is a copy of the data contained in $my_array[$i], not the actual data. To change the data in the array:
while ($i<sizeof($my_array)){
while(list($key,$val) = each($my_array[$i])){
$j = $i+1;
if ($key == "fruit"){
$my_array[$i][$key] = "ananas";
echo $my_array[$i][$key];
}
}
$i++;
}
And it's probably easier to use a foreach loop
each() doesn't pass the data as references, without modifying the loop that much:
if ($key == "fruit"){
$val = "ananas";
echo $val;
$my_array[$i][$key] = $val;
}
Of course, there are better ways to do that. But you wanted an answer that didn't change the loop structure.

Categories