Page 1 of 1
Get PHP variable name as string
Posted: Sun Dec 29, 2013 3:25 pm
by mikebr
Hi, I wonder if someone can shine some light on an easier way of getting a php variable name, for example the following would mean I need to know the name of the variable, which is fine as that is the case but is there maybe an easier way of having a variable such as
passed to a string variable as 'your_name'?:
Code: Select all
<?php
$your_name = 'Joe Blogs';
$your_age = 20;
$string = str_replace('$', '', str_replace('_', ' ', '$your_name')) . ': ' . $your_name;
$string .= str_replace('$', '', str_replace('_', '', '$your_age')) . ': ' . $your_age;
print($string);
?>
// Output
Your name: Joe Blogs
Your age: 20
Thanks in advance
Re: Get PHP variable name as string
Posted: Sun Dec 29, 2013 4:39 pm
by Celauran
What is it you're trying to do?
Re: Get PHP variable name as string
Posted: Sun Dec 29, 2013 4:58 pm
by mikebr
I am trying to get the actual variable name and pass it as a string, trying and cut out some work on a form processor script, I could either use two str_replace() nested or simpler just hand code the variable names into the strings, but rather than doing that I want to try and make it quick and simple to edit so if I added other form values it would be a simple copy paste on the block of code for that form element value and then quickly copy and past the additional variable name without having to stop and actually type the variable name where it is passed to build_content()... again also trying to cut down on code doing away with using str_replace() twice on each value:
Code: Select all
if (!is_badword($first_name, $fBadwords)) {
$messageContent .= build_content($first_name, str_replace('$', '', str_replace('_', '', '$first_name')));
} else ...
or just as:
Code: Select all
if (!is_badword($first_name, $fBadwords)) {
$messageContentStr .= build_content($first_name, 'First name');
} else ...
Code: Select all
<?php
print ($messageContentStr);
//Would output:
First name: Persons name
?>
The function buildContent() just builds the string for the body of the email for the name and content of each value passed to it.
Ideally it could just use:
Code: Select all
$messageContentStr .= buildContent($first_name);
and have the following
output:
First name: Persons name
Re: Get PHP variable name as string
Posted: Sun Dec 29, 2013 5:19 pm
by Celauran
If you're working with a form, you're already getting the data as an array, which makes things pretty simple, no?
Code: Select all
function humanize($string) {
return ucwords(str_replace('_', ' ', $string));
}
foreach ($_POST as $key => $value) {
$message .= humanize($key) . ": {$value}";
}
Or somesuch.
Re: Get PHP variable name as string
Posted: Sun Dec 29, 2013 5:42 pm
by mikebr
Humm... I forgot about $_POST
I will have a look at how I can use that, thanks for the help.