Using arrays with strings with a while loop - php

I am writing some code to create fields automatically, which will save me a load of time. I have got most of my code working, but I have came across one error with the code, which is preventing me from achieving my final goal.
The code is as follows:
while ($i <= $numFields) {
$type = "\$field{$i}_Data['type']";
$name = "\$field{$i}_Data['name']";
$placeholder = "\$field{$i}_Data['placeholder']";
$value = "\$field{$i}_Data['value']";
echo '<input type="'.$type.'" name="'.$name.'" placeholder="'.$placeholder.'" value="'.$value.'">';
$i++;
}
The $numFields variable is defined at the top of my script, and I have worked out that it is something to do with how I am setting the variables $type, $name etc.
The end result is to create inputs depending on properties set in variables at the top of the script, The only issue I am having is with the settings of the variables, as said above.
If any extra code/information is needed, feel free to ask.
Thank you.
NOTE - There is no physical PHP error, it's purely an error with this:
"\$field{$i}_Data['value']";

There are a few ways we could write this one out, but they are all extensions of variable expansion and/or variable-variables.
Basically, we just need to put the variable name in a string and then use that string as the variable (much like you're currently doing with $i inside the string):
$type = ${"field{$i}_Data"}['type'];
$name = ${"field{$i}_Data"}['name'];
// ...
However, if you don't mind an extra variable, this can be written more cleanly by saving it like so:
$data = ${"field{$i}_Data"};
$type = $data['type'];
$name = $data['name'];
// ...

Related

How to affect a string to a variable without redefining it

I'm working on a project, and it has a bunch of variables for some links that I define. But I want to add a string at the end of those variable only if I got some GET parameters. The thing is I don't want to have another huge amount of variables and I want to have the same name for the variables. After some research, I came with this operator .= which is perfect for me. I also made a for loop it works well for the variable value, but I don't have the same name.
Here is what I got:
$homeLink = $wURL.'government/'.$job.'/';
$databaseLink = $wURL.'government/'.$job.'/search/database';
$overviewLink = $wURL.'government/'.$job.'/overview';
// Other variables
if (!isset($_SESSION['steamid']) && isset($_GET['uID']) && isset($_GET['uToken'])) {
// redefine the variables like this:
$homeLink .= '?uID='.$userinfoVlife['id'].'&uToken='.$userinfoVlife['websiteMDP'];
/*
OUTPUT: $wURL.'government/'.$job.'/'.'?uID='.$userinfoVlife['id'].'&uToken='.$userinfoVlife['websiteMDP']
*/
// The for loop:
$arr = array($homeLink,$databaseLink,$overviewLink);
$nb = count($arr);
for ($i=0; $i < $nb ; $i++) {
$arr[$i] .= '?uID='.$userinfoVlife['id'].'&uToken='.$userinfoVlife['websiteMDP'];
echo $arr[$i]."<br>";
// have the same output that above but I have to call my variables with $arr[<a number>];
}
}
The thing is I don't want to have another huge amount of variables and I want to have the same name for the variables, any ideas on how I can proceed?
First, your 2 last links are actually both based on the first one, $homeLink:
$homeLink = $wURL.'government/'.$job.'/';
$databaseLink = $homeLink.'search/database';
$overviewLink = $homeLink.'overview';
then why not build the parameter string and then append it?
$homeLink = $wURL.'government/'.$job.'/'
$paramString = '';
if (!isset($_SESSION['steamid']) && isset($_GET['uID']) && isset($_GET['uToken'])) {
$paramString = '?uID='.$userinfoVlife['id'].'&uToken='.$userinfoVlife['websiteMDP'];
}
$databaseLink = $homeLink.'search/database'.$paramString;
$overviewLink = $homeLink.'overview'.$paramString;
$homeLink .= $paramString;
I don't get why you want to store your URLs in an array, these are different URLs, thus to be used in different contexts, having all of them in one array is of course possible but doesn't bring any value, in my opinion.
To conclude, if $userinfoVlife['websiteMDP'] contains a readable password, you definitely have a problem in your application architecture: it's very bad practice to handle raw passwords and it's even worse to pass it in the URL.

How to get variables from a different PHP file without executing the code?

I am trying to loop through all the php files listed in an array called $articleContents and extract the variables $articleTitle and $heroImage from each.
So far I have the following code:
$articleContents = array("article1.php", "article2.php"); // array of all file names
$articleInfo = [];
$size = count($articleContents);
for ($x = 0; $x <= $size; $x++) {
ob_start();
if (require_once('../articles/'.$articleContents[$x])) {
ob_end_clean();
$entry = array($articleContents[$x],$articleTitle,$heroImage);
array_push($articlesInfo, $entry);
}
The problem is, the php files visited in the loop have html, and I can't keep it from executing. I would like to get variables from each of these files without executing the html inside each one.
Also, the variables $articleTitle and $heroImage also exist at the top of the php file I'm working in, so I need to make sure the script knows I'm calling the variables in the external file and not the current one.
If this is not possible, can you please recommend an alternative method?
Thanks!
Don't do this.
Your PHP scripts should be for your application, not for your data. For your data, if you want to keep it file-based, use a separate file.
There are plenty of formats to choose from. JSON is quite popular. You can use PHP's built-in serialization as well, which has support for more PHP-native types but is not as portable to other frameworks.
A little hacky but seems to works:
$result = eval(
'return (function() {?>' .
file_get_contents('your_article.php') .
'return [\'articleTitle\' => $articleTitle, \'heroImage\' => $heroImage];})();'
);
Where your_article.php is something like:
<?php
$articleTitle = 'hola';
$heroImage = 'como te va';
The values are returned in the $result array.
Explanation:
Build a string of php code where the code in your article scripts are wrapped inside a function that returns an array with the values you want.
function() {
//code of your article.php
return ['articleTitle' => $articleTitle, 'heroImage' => $heroImage];
}
Maybe you must do some adaptations to the strings due <?php ?> tags placements.
Anyway, this stuff is ugly. I'm very sure that it can be refactored in some way.
Your problem (probably) comes down to using parentheses with require. See the example and note here.
Instead, format your code like this
$articlesInfo = []; // watch your spelling here
foreach ($articleContents as $file) {
ob_start();
if (require '../articles/' . $file) { // note, no parentheses around the path
$articlesInfo[] = [
$file,
$articleTitle,
$heroImage
];
}
ob_end_clean();
}
Update: I've tested this and it works just fine.

How to make a php variable based on two variable that vary

So i have this code, $value2 is an array of values that I edit.
I have .txt document for each of the variable in the array.. for exemple
sometext_AA.txt
sometext_BB.txt
I currently have over 50 text files, and it make a BIG BIG BIG php files because i have the following code made for each of the files for exemple sometext_AA.txt...
I would like to make one script(the following) so that one script will work for all of my $value2(I do not delete the old texts files when the value are changed so i am unable to just make script to read all different text file, it has to be done that it read the active $value2 and process them...
I am not even sure if I am on the good way but i really hope someone can help me out.
Thank you!
$value2 = array("AA","BB","CC");
foreach($value2 as $value3) {
foreach($random1_' .$value3' as $random2_' .$value3') {
$random3_' .$value3' = 'sometext_.$value3'.txt;
$random4_' .$value3' = json_encode(file_get_contents($random3_' .$value3'));
echo $random4_' .$value3';
}
}
This is a exemple of current text i have in my file, I have a very big php file, and, id like a code to make it simple
foreach($random1_AA as $random2_AA) {
$random3_AA = 'sometext_AA.txt;
$random4_AA = json_encode(file_get_contents($random3_AA));
echo $random4_AA;
}
foreach($random1_BB as $random2_BB) {
$random3_BB = 'sometext_BB.txt;
$random4_BB = json_encode(file_get_contents($random3_BB));
echo $random4_BB;
}
foreach($random1_CC as $random2_CC) {
$random3_CC = 'sometext_CC.txt;
$random4_CC = json_encode(file_get_contents($random3_CC));
echo $random4_CC;
}
foreach($random1_DD as $random2_DD) {
$random3_DD = 'sometext_DD.txt;
$random4_DD = json_encode(file_get_contents($random3_DD));
echo $random4_DD;
}
I think that this is what you are looking for, using the $var_{$var_in_var} syntax that PHP allows (so you can include a variable in a variable name).
$value2 = array("AA","BB","CC");
foreach($value2 as $value3) {
foreach($random1_{$value3} as $random2_{$value3}) {
$random3_{$value3} = 'sometext_'.$value3.'.txt';
$random4_{$value3} = json_encode(file_get_contents($random3_{$value3}));
echo $random4_{$value3};
}
}
However, I stongly advise you to consider the following points in order to make your code maintainable:
Use appropriate variable names representing the real content of each variable (you shoud never use "value1", "value2", etc. as the name tells nothing about the variable content).
Don't use variables in variable names unless absolutely necessary, which is not your case. You can use arrays, which are better suited for doing that.
In fact, I don't even know what $random1_XX and $random2_XX are supposed to be. I don't see you defining them in the code sample you posted.
Here is an example of how clear and concise you code may be if you use my advice and if all you need to read all the files and print them in JSON format (which is the only thing the program sample you posted would be doing after corrections).
$file_codes = array('AA', 'BB', 'CC');
foreach($file_codes as $file_code) {
echo json_encode(file_get_contents('sometext_'.$file_code.'.txt'));
}
Of course, if you have anything else in your program (maybe some code using the variables $random3_XX and $random4_XX?), I cannot guess what it is so I can't really offer you help to optimize this code.

a function for creating shortname style variables in PHP

I'm just learning PHP, and I'm sure I'm not the first person to try something like this, but maybe because I didn't know what to call it, I couldn't find any other examples or questions on here or from a search on google.
I wanted to create a function which takes two parameters and uses them to create all the short style variables I'll be using later in my script.
My problem is where normally the syntax to create a short variable is something like:
$var = $_METHOD['var'];
but I'm trying to do this using variables and don't know how to get the syntax right. Here's my code:
<?php
session_start();
function shortnames($some_vars, $type) {
for ($i = 0; $i<(count($some_vars)); $i++) {
$$some_vars[$i] = $_$type['$some_vars[$i]'];
echo $$some_vars[$i].' = '.$some_vars[$i].'<br />';
}
}
$post_vars = array(lastname,firstname,payment);
$session_vars = array(sessiontxt,province,city,venue,regfee);
shortnames($session_vars,session);
shortnames($post_vars,post);
?>
Thanks for helping a beginner!!

Build a variable name in PHP out of two variables

Depending on the current page, I would like to change the css of the chosen menu module and make others different, etc. All that while building dynamically the page before loading.
My problem is that I have a serie of variables going by this structure :
$css_(NAME_OF_MODULE)
To know what variable must be set , I have another variable I received in parameters of this functions, called
$chosen_menu
Say $chosen_Menu = "C1", I would like to add content to $css_C1. Thus, what I want is to create a variable name out of 2 variables, named $css_C1
I have tried :
${$css_.$chosen_menu} = "value";
But it doesnt seem to work. Any clue ?
That probably won't just work. PHP supports full indirection though, so something like this will work.
$varName = $css."_".$chosen_menu;
$$varName = "value";
If not, it will probably be attempting to interpret $css_ as a variable name in your second code sample, so just change that to $css."_".$chosen_menu.
$nr = 1;
${'name' . $nr} = 20 ;
var_dump($name1);
Check out http://php.net/manual/en/language.variables.php
You should be able to use:
$menu = $css . '_' .$chosen_menu;
$$menu = 'some value';
or
${$menu} = 'some value';
I'm not sure if I get you right, but how about this:
${$css."_".$chosen_menu} = "value";

Categories