How do I go about setting a string as a literal variable in PHP? Basically I have an array like
$data['setting'] = "thevalue";
and I want to convert that 'setting' to $setting so that $setting becomes "thevalue".
Thanks for any help!
See PHP variable variables.
Your question isn't completely clear but maybe you want something like this:
//Takes an associative array and creates variables named after
//its keys
foreach ($data as $key => $value) {
$$key = $value;
}
extract() will take the keys of an array and turn them into variables with the corresponding value in the array.
${'setting'} = "thevalue";
It may be evil, but there is always eval.
$str = "setting";
$val = "thevalue";
eval("$" . $str . " = '" . $val . "'");
Related
Here is an example of what I am trying to accomplish:
$array['aaa']['bbb']['ccc'] = "value";
$subarray = "['bbb']['ccc']";
echo $array['aaa']$subarray; // these 2 echos should be the same
echo $array['aaa']['bbb']['ccc']; // these 2 echos should be the same
It should display the same as $array['aaa']['bbb']['ccc'] i.e., "value".
This doesnt work, of course. But is there some simple solution to this?
There could be some function and the $subarrayvalue may be used as a parametr and/or as an array itself like: $subarray = array('bbb','ccc'); I dont mind as long as it worsk.
You could try something like below.
$subarray = "['bbb']['ccc']";
$temp = parse_str("\$array['aaa']".$subarray);
echo $temp;
OR To ignore single quotes -
$subarray = "[\'bbb\'][\'ccc\']";
$temp = parse_str("\$array[\'aaa\']".$subarray);
echo $temp;
Also you may refer - http://php.net/manual/en/function.parse-str.php
Just try using array chunk function http://php.net/manual/en/function.array-chunk.php
here is what actually works!!
$array['aaa']['bbb']['ccc'] = "value";
$subarray = "['bbb']['ccc']";
$string = 'echo $array[\'aaa\']' . $subarray . ';';
eval($string);
Edit: The aim of my method is to delete a value from a string in a database.
I cant seem to find the answer for this one anywhere. Can you concatenate inside a str_replace like this:
str_replace($pid . ",","",$boom);
$pid is a page id, eg 40
$boom is an exploded array
If i have a string: 40,56,12 i want to make it 56,12 however without the concatenator in it will produce:
,56,12
When I have the concat in the str_replace it doesnt do a thing. Is this possible?
Answering your question: yes you can. That code works as you would expect it to.
But this approach is wrong. It will not work for $pid = 12; (last element, without trailing coma) and will incorrectly replace 40, in $boom = '140,20,12';
You should keep it in array, search for unwanted value, if found unset it from the array and then implode with coma.
$boom = array_filter($boom);
$key = array_search($pid, $boom);
if($key !== false){
unset($boom[$key]);
}
$boom = implode(',',$boom);
[+] Your code does not work because $boom is an array, and str_replace operates on string.
As $boom is an array, you don't need to use array on your case.
Change this
$boom = explode(",",$ticket_array);
$boom = str_replace($pid . ",","",$boom);
$together = implode(",",$boom);
to
$together = str_replace($pid . ",","",$ticket_array);
Update: If you want still want to use array
$boom = explode(",",$ticket_array);
unset($boom[array_search($pid, $boom)]);
$together = implode(",",$boom);
After you have edited it becomes clear that you want to remove the value of $pid from the array $boom which contains one number as a value. You can use array_search to find if it is in at if in with which key. You can then unset the element from $boom:
$pid = '40';
$boom = explode(',', '40,56,12');
$r = array_search($pid, $boom, FALSE);
if ($r !== FALSE) {
unset($boom[$r]);
}
Old question:
Can you concatenate inside a str_replace like this: ... ?
Yes you can, see the example:
$pid = '40';
$boom = array('40,56,12');
print_r(str_replace($pid . ",", "", $boom));
Result:
Array
(
[0] => 56,12
)
Which is pretty much like you did so you might be looking for the problem at the wrong place. You can use any string expression for the parameter.
It might be easier for you if you're unsure to create a variable first:
$pid = '40';
$boom = array('40,56,12');
$search = sprintf("%d,", $pid);
print_r(str_replace($search, "", $boom));
You should store your "ticket array" in a separate table.
And use regular SQL queries (UPDATE, DELETE) to manipulate it.
A relational word in the name of your database is for the reason. And you are abusing this smart software with such a barbaric approach.
You could use str_split, it converts a string to an array, then with a foreach loop echo all the values except the first one.
$numbers_string="40,56,12";
$numbers_array = str_split($numbers_string);
//then, when you have the array of numbers, you could echo every number except the first separating them with a comma
foreach ($numbers_array as $key => $value) {
if ($key > 0) {
echo $value . ", ";
}
}
If you want is to skip a value not by it's position in the array, but for it's value then you could do this instead:
$unwanted_value="40";
foreach ($numbers_array as $key => $value) {
if ($value != $unwanted_value) {
echo $value . ", ";
}
else {
unset($numbers_array[$key]);
$numbers_array = array_values($numbers_array);
var_dump($numbers_array);
}
}
I have an array holding this data:
Array (
[1402377] => 7
[1562441] => 7
[1639491] => 9
[1256074] => 10
)
How can create a string that contains the keys of the above array?
Essentially, I need to create a comma separated string that consists of an array's keys
The string would look like: 'key','key','key'
Do I need to create a new array consisting of the keys from an existing array?
The reason I need to do this is because I will be querying a MySQL database using a WHERE in () statement. I would rather not have to query the database using a foreach statement. Am I approaching this problem correctly?
I've tried using a while statement, and I'm able to print the array keys that I need, but I need those keys to be an array in order to send to my model.
The code that allowed me to print the array keys looks like this:
while($element = current($array)) {
$x = key($array)."\n";
echo $x;
next($array);
}
$string = implode(',', array_keys($array));
By the way, for looping over an array consider not using current and next but use foreach:
foreach ($array as $key => $value) {
//do something
}
This will automatically iterate over the array until all records have been visited (or not at all if there are no records.
$keys = array_keys($array);
$string = implode(' ',$keys);
In your case, were you are using the result in a IN clause you should do:
$string = implode(',', $keys);
$yourString = '';
foreach($yourArr as $key => $val) {
$yourString .=$key.",";
}
echo rtrim($yourString, ",");
//OR
$yourString = implode(",", array_keys($yourArray));
See : array_keys
implode(', ', array_keys($array));
Use php array_keys and implode methods
print implode(PHP_EOL, array_keys($element))
The string would look like: 'key','key','key'
$string = '\'' . implode('\',\'', array_keys($array)) . '\'';
Imploding the arguments and interpolating the result into the query can cause an injection vulnerability. Instead, create a prepared statement by repeating a string of parameter placeholders.
$paramList = '(' . str_repeat('?, ', count($array) - 1) . '?)'
$args = array_keys($array);
$statement = 'SELECT ... WHERE column IN ' . $paramList;
$query = $db->prepare($statement);
$query->execute($args);
Now I got the string of an array, like this :
$str = "array('a'=>1, 'b'=>2)";
How can I convert this string into real array ? Is there any "smart way" to do that, other that use explode() ? Because the "string" array could be very complicated some time.
Thanks !
Use php's "eval" function.
eval("\$myarray = $str;");
i don't know a good way to do this (only evil eval() wich realy should be avoided).
but: where do you get that string from? is it something you can affect? if so, using serialize() / unserialize() would be a much better way.
With a short version of the array json_decode works
json_decode('["option", "option2"]')
But with the old version just like the OP's asking it doesn't. The only thing it could be done is using Akash's Answer or eval which I don't really like using.
json_decode('array("option", "option2")')
You could write the string to a file, enclosing the string in a function definition within the file, and give the file a .php extension.
Then you include the php file in your current module and call the function which will return the array.
You'd have to use eval().
A better way to get a textual representation of an array that doesn't need eval() to decode is using json_encode() / json_decode().
If you can trust the string, use eval. I don't remember the exact syntax, but this should work.
$arr = eval($array_string);
If the string is given by user input or from another untrusted source, you should avoid eval() under all circumstances!
To store Arrays in strings, you should possibly take a look at serialize and unserialize.
Don't use eval() in any case
just call strtoarray($str, 'keys') for array with keys and strtoarray($str) for array which have no keys.
function strtoarray($a, $t = ''){
$arr = [];
$a = ltrim($a, '[');
$a = ltrim($a, 'array(');
$a = rtrim($a, ']');
$a = rtrim($a, ')');
$tmpArr = explode(",", $a);
foreach ($tmpArr as $v) {
if($t == 'keys'){
$tmp = explode("=>", $v);
$k = $tmp[0]; $nv = $tmp[1];
$k = trim(trim($k), "'");
$k = trim(trim($k), '"');
$nv = trim(trim($nv), "'");
$nv = trim(trim($nv), '"');
$arr[$k] = $nv;
} else {
$v = trim(trim($v), "'");
$v = trim(trim($v), '"');
$arr[] = $v;
}
}
return $arr;
}
How can i array a string, in the format that $_POST does... kind of, well i have this kind of format coming in:
101=1&2020=2&303=3
(Incase your wondering, its the result of jQuery Sortable Serialize...
I want to run an SQL statement to update a field with the RIGHT side of the = sign, where its the left side of the equal sign? I know the SQL for this, but i wanted to put it in a format that i could use the foreach($VAR as $key=>$value) and build an sql statement from that.. as i dont know how many 101=1 there will be?
I just want to explode this in a way that $key = 101 and $value = 1
Sounds confusing ;)
Thanks so so much in advanced!!
See the parse_str function.
It's not the most intuitive function name in PHP but the function you're looking for is parse_str(). You can use it like this:
$myArray = array();
parse_str('101=1&2020=2&303=3', $myArray);
print_r($myArray);
One quick and dirty solution:
<?php
$str = "101=1&2020=2&303=3";
$VAR = array();
foreach(explode('&', $str) AS $pair)
{
list($key, $value) = each(explode('=', $pair));
$VAR[$key] = $value;
}
?>
parse_str($query_string, $array_to_hold_values);
$input = "101=1&2020=2&303=3";
$output = array();
$exp = explode('&',$input);
foreach($exp as $e){
$pair = explode("=",$e);
$output[$pair[0]] = $pair[1];
}
Explode on the & to get an array that contains [ 101=1 , 2020=2 , 303=3 ] then for each element, split on the = and push the key/value pair onto a new array.