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;
}
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);
I have many links with parameter number - value is numbers between 1-1000
http://mysite.com?one=2&two=4&number=2
http://mysite.com?one=2&two=4&four=4&number=124
http://mysite.com?one=2&three=4&number=9
http://mysite.com?two=4&number=242
http://mysite.com?one=2&two=4&number=52
How can i remove from this parameter and value with PHP? I would like receive:
http://mysite.com?one=2&two=4
http://mysite.com?one=2&two=4&four=4
http://mysite.com?one=2&three=4
http://mysite.com?two=4
http://mysite.com?one=2&two=4
Try this:
$str = 'http://mysite.com?one=2&two=4&number=2';
$url = parse_url($str);
parse_str($url['query'], $now );
unset($now['number']);
foreach($now as $key=>$value) :
if(is_bool($value) ){
$now[$key] = ($value) ? 'true' : 'false';
}
endforeach;
$options_string=http_build_query($now);
echo $url = 'http://mysite.com?'.$options_string;
Reference : PHP function to build query string from array - not http build query
Like this
$urls = '
http://mysite.com?one=2&two=4&number=2
http://mysite.com?one=2&two=4&four=4&number=124
http://mysite.com?one=2&three=4&number=9
http://mysite.com?two=4&number=242
http://mysite.com?one=2&two=4&number=52
';
echo '<pre>';
echo preg_replace('#&number=\d+#', '', $urls);
you can build a redirection after building a new URL with $_GET['one']
Use bellow steps,this is clear aproach
1- Parse the url into an array with parse_url()
2- Extract the query portion, decompose that into an array
3- Delete the query parameters you want by unset() them from the array
4- Rebuild the original url using http_build_query()
hope this help you
You could use parse_str() which parses the string into variables. In that way you can separate them easily
I wrote example of code.
<?php
$arr = array();
$arr[] = 'http://mysite.com?one=2&two=4&number=2';
$arr[] = 'http://mysite.com?one=2&two=4&four=4&number=124';
$arr[] = 'http://mysite.com?one=2&three=4&number=9';
$arr[] = 'http://mysite.com?two=4&number=242';
$arr[] = 'http://mysite.com?one=2&two=4&number=52';
function remove_invalid_arguments(array $array_invalid, $urlString)
{
$info = array();
parse_str($urlString, $info);
foreach($array_invalid as $inv)
if(array_key_exists($inv,$info)) unset($info[$inv]);
$ret = "";
$i = 0;
foreach($info as $k=>$v)
$ret .= ($i++ ? "&" : ""). "$k=$v"; //maybe urlencode also :)
return $ret;
}
//usage
$invalid = array('number'); //array of forbidden params
foreach($arr as $k=>&$v) $v =remove_invalid_arguments($invalid, $arr[1]);
print_r($arr);
?>
Working DEMO
If "&number=" is ALWAYS after the important parameters, I'd use str_split (or explode).
The more sure way is to use parse_url(),parse_str() and http_build_query() to break the URLs down and put them back together.
As per example of your url -
$s='http://mysite.com?one=2&two=4&number=2&number2=200';
$temp =explode('&',$s);
array_pop($temp);
echo $newurl = implode("&", $last);
Output is :http://mysite.com?one=2&two=4&number=2
Have a look at this one using regex: (as an alternative, preferably use a parser)
(.+?)(?:&number=\d+)
Assuming &number=2 is the last parameter. This regex will keep the whole url except the last parameter number
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 . "'");
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.
How to find memory used by an object in PHP? (c's sizeof). The object I want to find out about is a dictionary with strings and ints in it so it makes it hard to calculate it manually. Also string in php can be of varied length depending on encoding (utf8 etc) correct?
You could use memory_get_usage().
Run it once before creating your object, then again after creating your object, and take the difference between the two results.
To get an idea about the objects size, try
strlen(serialize($object));
It is by no means accurate, but an easy way to get a number for comparison.
If you need to know the size of an already created object or array, you can use the following code to find it out.
<?php
function rec_copy($src) {
if (is_string($src)) {
return str_replace('SOME_NEVER_OCCURING_VALUE_145645645734534523', 'XYZ', $src);
}
if (is_numeric($src)) {
return ($src + 0);
}
if (is_bool($src)) {
return ($src?TRUE:FALSE);
}
if (is_null($src)) {
return NULL;
}
if (is_object($src)) {
$new = (object) array();
foreach ($src as $key => $val) {
$new->$key = rec_copy($val);
}
return $new;
}
if (!is_array($src)) {
print_r(gettype($src) . "\n");
return $src;
}
$new = array();
foreach ($src as $key => $val) {
$new[$key] = rec_copy($val);
}
return $new;
}
$old = memory_get_usage();
$dummy = rec_copy($src);
$mem = memory_get_usage();
$size = abs($mem - $old);
?>
This essentially creates a copy of the array structure and all of its members.
A not 100% accurate, but still working version is also:
<?php
$old = memory_get_usage();
$dummy = unserialize(serialize($src));
$mem = memory_get_usage();
$size = abs($mem - $old);
Hope that helps for cases where the object is already build.
This method converts the array to a json string and determines the length of that string. The result should be fairly similar to the size of the array (both will have delimiters to partition members of the array or the stringified json)
strlen(json_encode(YourArray))
this method could be help you:
function getVariableUsage($var) {
$total_memory = memory_get_usage();
$tmp = unserialize(serialize($var));
return memory_get_usage() - $total_memory;
}
$var = "Hey, what's you doing?";
echo getVariableUsage($var);
https://www.phpflow.com/
I don't know that there is a simple way to get the size of an object in PHP. You might just have to do an algorith that
Counts the ints
Multiplies number of ints by size of an int on hard disk
Convert characters in strings to ASCII and
Multiply the ASCII values by how much they take up on disk
I'm sure there is a better way, but this would work, even though it would be a pain.