Can you turn PHP text into a variable? - php

I was wondering if it was possible to dynamically create variables like so:
$sender = $email = $number = $message = "";
foreach ($_POST as $key => $value) {
if isset & !empty //loosely typed
$+key = $value // can something like this be done?
}
if so how?

PHP does have variable variables, but you don't need that here. I think a simple associative array or object will work just fine for you.
$data = array(
'sender' => 'Someone',
'email' => 'test#example.com',
'number' => 12345,
'message' => 'some message'
);
echo $data['sender']; // Someone

Something like this should work. But I wouldn't do it unless you completely trust the data and if its POST data then access it like $_POST['key']
foreach ($_POST as $key => $value) {
if isset & !empty //loosely typed
${$key} = $value // can something like this be done?
}

There is a PHP function called extract which does what you are looking for.
http://nz2.php.net/extract

Related

How to store each array value in a variable with PHP

I have an array that looks something like this:
Array
(
[2] => http://www.marleenvanlook.be/admin.php
[4] => http://www.marleenvanlook.be/checklogin.php
[5] => http://www.marleenvanlook.be/checkupload.php
[6] => http://www.marleenvanlook.be/contact.php
)
What I want to do is store each value from this array to a variable (using PHP). So for example:
$something1 = "http://www.marleenvanlook.be/admin.php";
$something2 = "http://www.marleenvanlook.be/checklogin.php";
...
You can use extract():
$data = array(
'something1',
'something2',
'something3',
);
extract($data, EXTR_PREFIX_ALL, 'var');
echo $var0; //Output something1
More info on http://br2.php.net/manual/en/function.extract.php
Well.. you could do something like this?
$myArray = array("http://www.marleenvanlook.be/admin.php","http://www.marleenvanlook.be/checklogin.php","etc");
$i = 0;
foreach($myArray as $value){
${'something'.$i} = $value;
$i++;
}
echo $something0; //http://www.marleenvanlook.be/admin.php
This would dynamically create variables with names like $something0, $something1, etc holding a value of the array assigned in the foreach.
If you want the keys to be involved you can also do this:
$myArray = array(1 => "http://www.marleenvanlook.be/admin.php","http://www.marleenvanlook.be/checklogin.php","etc");
foreach($myArray as $key => $value){
${'something'.$key} = $value;
}
echo $something1; //http://www.marleenvanlook.be/admin.php
PHP has something called variable variables which lets you name a variable with the value of another variable.
$something = array(
'http://www.marleenvanlook.be/admin.php',
'http://www.marleenvanlook.be/checklogin.php',
'http://www.marleenvanlook.be/checkupload.php',
'http://www.marleenvanlook.be/contact.php',
);
foreach($something as $key => $value) {
$key = 'something' . $key;
$$key = $value;
// OR (condensed version)
// ${"something{$key}"} = $value;
}
echo $something2;
// http://www.marleenvanlook.be/checkupload.php
But the question is why would you want to do this? Arrays are meant to be accessed by keys, so you can just do:
echo $something[2];
// http://www.marleenvanlook.be/checkupload.php
What I would do is:
$something1 = $the_array[2];
$something2 = $the_array[4];

Push associated variables into array in PHP

I have a loop and each time the loop runs I need to add two variables to an array. What I am trying right now is:
$attach_array['outline'] = array();
foreach ($_POST['attachment'] as $key => $value) {
$attachmentName = $value['name'];
$path = "1";
$name = "alsdkjf";
$attach_array['outline']['path']=$path;
$attach_array['outline']['name']=$name;
}
Then later in the script I try to get these values out for PHPMAILER:
foreach ($attach_array['outline'] as $key => $value) {
$mail->AddAttachment($value['path'], $value['name']);
}
This and other attempts are not working so I'm hoping for some help on putting $name and $path into an array in my first loop to use later.
You are overriding the same variables on each loop. You should do something like this:
$attach_array['outline'][] = array('path' => $path, 'name' => $name);
By doing this, now all the path and values will remain on the array as separate items. You dont have to change the code you are using it from.

Does it exist any function to dynamically create variables from the key value pair of an array?

Let's say I have this array,
$array = array(
'name' => 'hermet',
'emails' => array ('hermet#example.com',
'hermet#example.net');
);
So this way echo $array ['name'] == 'hermet' prints true. I would like to know if there is a function already embedded in PHP that let me do this:
echo $name == 'hermet'; // obviously 'false'
foreach ($array as $key => $value) {
$aux = $key;
$$aux = $value;
}
echo $name == 'hermet'; // now prints 'true'
It seems to work even with a multidimensional array but I don't know if PHP has already any function to do that.
Thank you in advance.
You might be looking for extract
$array = array(
'name' => 'hermet',
'emails' => array ('hermet#example.com',
'hermet#example.net')
);
extract($array);
var_dump($emails);
echo $name;
-- EDIT: If you are concerned about Paul's remark, supply EXTR_SKIP to the second argument of extract, that way it won't overwrite variable in case you've already defined it prior to calling extract.
$name = 'jason';
extract($array, EXTR_SKIP);
echo $name; // still 'jason'

php values and keys setting web address

i am trying to set the web addresses as the valves and set the keys to be short names for the sites. Not sure where im going wrong. Everytime i try and run it it keeps saying line 11 which is $http://www.yahoo.co.uk/= array( key => value,("yahoo_uk");
$http://www.yahoo.co.uk/= array( key => value,("yahoo_uk");
foreach ($array as $key =>$value) {
echo $value;
}
?>
</body>
wow :P There are so many syntax errors I don't even know where to begin
Here's the correct syntax
$array = array('http://www.yahoo.co.uk' => 'yahoo_uk');
Read this chapter of the manual:
http://php.net/manual/en/language.types.array.php
It seems you intend to do something like:
$urls = array();
$urls['yahoo_uk'] = "http://www.yahoo.co.uk/";
This initializes an array to store URLs, then creates an array member with the short name yahoo_uk as key, and its corresponding URL as the value.
You can then access it with foreach:
foreach ($urls as $name => $url) {
echo "name: $name, url: $url\n";
}
I assume this is what you were going for
<?php
$array = array('http://www.yahoo.co.uk/' => 'yahoo_uk');
foreach ($array as $key =>$value) {
echo $value;
}
?>
You are trying to set constants within your array and you're using incorrect PHP syntax. Try this instead:
$urls = array('yahoo_uk' => 'http://www.yahoo.co.uk/');
foreach ($urls as $key => $value) {
echo $value;
}
Or calling a single value like this:
echo $urls['yahoo_uk']; // http://www.yahoo.co.uk/
Also, your question is very vague and hard to understand.
Try this code:
$yahoo = array_assoc('http://www.yahoo.co.uk/' => 'yahoo_uk');
foreach ($yahoo as $key => $value) {
echo $value;
}
?>

How to check for optional fields in $_POST

At the moment my code looks like this:
# Assign values for saving to the db
$data = array(
'table_of_contents' => $_POST['table_of_contents'],
'length' => $_POST['length']
);
# Check for fields that may not be set
if ( isset($_POST['lossless_copy']) )
{
$data = array(
'lossless_copy' => $_POST['lossless_copy']
);
}
// etc.
This would lead to endless if statements though... Even with the ternary syntax it's still messy. Is there a better way?
How about this:
// this is an array of default values for the fields that could be in the POST
$defaultValues = array(
'table_of_contents' => '',
'length' => 25,
'lossless_copy' => false,
);
$data = array_merge($defaultValues, $_POST);
// $data is now the post with all the keys set
array_merge() will merge the values, having the later values override the previous ones.
If you don't want to trust array_merge() then you can do a foreach() loop.
You could build an array of optional fields:
$optional = array('lossless_copy', 'bossless_floppy', 'foo');
foreach ($optional as $field) {
if (isset($_POST[$field])) {
$data[$field] = $_POST[$field];
}
}
foreach ($_POST as $key => $value) {
$data[$key] = $value;
}
remember to sanitize your $_POST values!
edit: if you're looking to match up optional $_POST values with fields that may or may not exist in your table, you could do something like this (i'm assuming you're using mysql):
$fields = array();
$table = 'Current_Table';
// we are not using mysql_list_fields() as it is deprecated
$query = "SHOW COLUMNS from {$table}";
$result = mysql_query($query);
while ($get = mysql_fetch_object($result) ) {
$fields[] = $get->Field;
}
foreach($fields as $field) {
if (isset($_POST[$field]) ) {
$data[$field] = $_POST[$field];
}
}
$formfields = $_POST;
$data = array();
foreach(array_keys($formfields) as $fieldname){
$data[$fieldname] = $_POST[$fieldname];
}
This will add all fields that are returned including submit. If you need to know if a checkbox has not been checked, you're going to have to use code like you posted. If you only care about checkboxes that are checked, you can use the above code.
This would probably not work for multiple formfields using the same name, like radio buttons.
EDIT: Use Owen's code, it's cleaner, mine is a more verbose version of the same thing.

Categories