I am unserializing below string but its not returning anything.
a:57:{s:10:"THEME_NAME";s:5:"green";s:16:"PUBLIC_ADS_LIMIT";s:1:"5";s:17:"PUBLIC_EDIT_LIMIT";s:1:"5";s:8:"SITENAME";s:10:"Abcdubai";s:5:";}
The data you're unserializing is wrong
a:57{s:10:"THEME_NAME";s:5:"green";s:16:"PUBLIC_ADS_LIMIT";s:1:"5";s:17:"PUBLIC_EDIT_LIMIT";s:1:"5";s:8:"SITENAME";s:10:"Abcdubai";s:5:";}
if you try to unserialize it with error reporting E_ALL you will see a notice
$data = 'a:57{s:10:"THEME_NAME";s:5:"green";s:16:"PUBLIC_ADS_LIMIT";s:1:"5";s:17:"PUBLIC_EDIT_LIMIT";s:1:"5";s:8:"SITENAME";s:10:"Abcdubai";s:5:";}';
var_dump($data);
you will get
Notice: unserialize(): Error
because
a:57 is the array length and from the data you have it's clearly not 57.
s: points to the length of string s:10:"Abcdubai" the string Abcdubai is not 10 in length it's 8 so you need to change that to s:8:"Abcdubai"
Finally you have s:5:"; at the end for the same reason s:5 means a string with 5 characters in length and it's empty with a one double quote
<?php
// this the valid data
$data = 'a:4:{s:10:"THEME_NAME";s:5:"green";s:16:"PUBLIC_ADS_LIMIT";s:1:"5";s:17:"PUBLIC_EDIT_LIMIT";s:1:"5";s:8:"SITENAME";s:8:"Abcdubai";}';
$data = unserialize($data);
// accessing the valid serialized data
echo $data['THEME_NAME'];
echo $data['PUBLIC_ADS_LIMIT'];
echo $data['PUBLIC_EDIT_LIMIT'];
echo $data['SITENAME'];
you can try this method to solve formatting issues
function fixUnserializeFormatting($data){
// fix string length (will fix s:)
$data = preg_replace('!s:(\d+):"(.*?)";!e', "'s:'.strlen('$2').':\"$2\";'", $data);
// remove empty matches with one double qoute
$data = preg_replace('/s\:+[0-9]+\:";/i', '', $data);
// trying to get the right array length
$strings = substr_count($data,';') / 2;
// fixing array length
$data = preg_replace('/^a:+[0-9]+:/i', "a:{$strings}:", $data);
// finally returning the formatted data
return $data;
}
Usage
$data = 'a:57:{s:10:"THEME_NAME";s:5:"green";s:16:"PUBLIC_ADS_LIMIT";s:1:"5";s:17:"PUBLIC_EDIT_LIMIT";s:1:"5";s:8:"SITENAME";s:10:"Abcdubai";s:5:";}';
$data = fixUnserializeFormatting($data);
var_dump(unserialize($data));
Related
I have a list of numbers then I want to put comma on each number works fine, but the problem if number exceed to 14 my output become scientific format
Like this 1,.,1,1,1,1,1,1,1,1,1,E,+,2,8
but i want to be like this 1,1,1,1,1,1,1,1,0,0,0,0,1,1,1,
here's sample code below
<?php
$val = 11111111110000000000000000111;
$val = (string)$val; // convert into a string
$arr = str_split($val, "1"); // break string in 3 character sets
$val_new = implode(",", $arr); // implode array with comma
echo $val_new;
?>
Thanks
This is because it exceeds the max value of an integer. There is nothing much you can do about it.
Input that exceeds this limit will always be converted to a floating point representation. This means the input should immediatly be formatted as a string:
$val = "11111111110000000000000000111";
$arr = str_split($val, 1); // break string in 3 character sets
$val_new = implode(",", $arr); // implode array with comma
echo $val_new;
This happens because the number is too large, so php automatically converts it into the scientific format. you can avoid this by defining the number as string initially (by putting it inside quotations)...try changing your code to this:
$val = "11111111110000000000000000111";
and remove this line:
$val = (string)$val; // convert into a string
let me know how it went.
This is my php function it must return "5" but it returns nothing.
<?php
function get_second($num){
$second = $num[1]; //must return second number of the variable.
return $second;
}
$numbers=456789;
echo get_second($numbers);
?>
When I tried out this code, this returns nothing (NULL, empty).
But I tried out this function below, worked perfectly.
<?php
function get_second($num){
$second = $num[1]; //must return second number of the variable.
return $second;
}
$numbers=$_POST['number_input'];//that includes numbers
echo get_second($numbers);
?>
This code returns me second number of the post data. What I must do to work my First function? What is the difference between first $numbers variable and second $numbers variable?
Here the problem has to be better defined: how to get the second digit from a number. Your initial approach was correct in logic, but incorrect in the assumption that a number is a order set of characters. Only strings are ordered set of characters. Once you transform the integer 45678 to the string 45678 you can easily intercept the second character by using substr or even directly the string - because in PHP strings can be treated as arrays of characters.
#RamRaider solution is better than other have suggested but is overkill to use preg_split. Other solutions ask you to modify the type of the variable which is not done by adding quotes, but is done by casting to string, which is simpler and faster than a regular expression and you maintain your original variable in original form and your original function definition.
function get_second($num){
$second = $num[1]; //must return second number of the variable.
return $second;
}
$numbers = 456789;
// casting to string
echo get_second((string)$numbers);
// or transform to string by concatenation to a string
echo get_second($numbers ."");
// even quoting works
echo get_second("$numbers");
// using strval
echo get_second(strval($numbers));
// using settype
echo get_second(settype($numbers, "string"));
Try this: (add quotes to your integer variable)
<?php
function get_second($num){
$second = $num[1]; //must return second number of the variable.
return $second;
}
$numbers="456789";
echo get_second($numbers);
?>
If you want to get Character by its number then you can use substr()
function get_second($num)
{
return substr($num,1,1);
}
$numbers="456789";
echo get_second($numbers);
you are declaring a number in the $number variable.
if you want to view the second element than you have to use string.
try
$numbers= "456789";
it will output 5.
You could use preg_split to force an array from which you can choose any number by index, like:
$number=12358397;
function get_number($num,$i){
$num=preg_split( '#^\d$#', $num );
return $num[0][$i];
}
echo ' [1] > > > ' . get_number($number,1);
I get and error array to string conversion error on line 11
I need to compare $result array with $file array and then over write FILE with $result data. In other words, FILE and the data it contains is continuously being updated with $result
compare -> overwrite -> repeat at next execution.
Note: .db file is empty at first cycle but becomes populated at first write.
sample code with Array to string conversion error:
<?php
$id = $argv[1]; //variable for inbound
$result = array(
'return' => array(
array(1,2,3),
array(6,2,3),
array(3,2,3),
)
);
function getdiff($new, $old) {
$diff = array_intersect($new, $old);
return $diff;
}
$old = file_exists('1.db') ? json_decode(file_get_contents('1.db'), 1) : array();
$arrayDiffresult = getdiff( $result, $old);
file_put_contents('1.db', json_encode($result));
print_r(
getdiff($result, $old)
);
?>
I have a second method I have tried and I get the same error, at the comparison point line 9.
$result = array(
'return' => array(
array(1,2,3),
array(5,2,3),
array(3,2,3),
)
);
$lines = file("myDB.db");
$arrayDiffresult = array_diff ( $result['return'], $lines);
file_put_contents('myDB.db', print_r($result['return'], true));
I believe array_intersect is only used in one dimensional arrays, and it is attempting to treat the nested arrays as a string for equality comparison. However looking at the documentation show the function array_uintersect where you can write your own comparison function as a callback. You didn't provide much information as to what the requirements are but if you do I'd be happy to help
I have an array with $post_id as keys. When save the $data, I saved it as a string:
foreach( $data as $post_id => $details )
$string .= "-pid-$post_id-$details";
When use the data, I need to convert it back to array with $post_id as key and $details as value. How to explode it when I don't know what is the $post_id ?
Don't do it this way. if you need to serialize a string use json_encode():
$string = json_encode($data);
Then, when you need to decode it again:
$data = json_decode($string);
Safe and easy.
Here's the PHP reference: json_encode()
php has a method called serialize which will take an array (such as $_POST) and convert it to a string that can then be recreated into an array with unserialize
<?php
// $_POST looks like this for example:
// $_POST['value'] = 100;
$string = serialize($_POST);
echo $string; // Prints '"a":1:{s:5:"value";s:3:"100";}'
$data = unserialze($string);
print_r($data); // Prints Array[0] ( 'value' => '100' )
?>
I won't lecture about not sanitizing user input, but SANITIZE USER INPUT.
serialize
unserialize
Note that this is a binary string which may include null bytes, and needs to be stored and handled as such. For example, serialize() output should generally be stored in a BLOB field in a database, rather than a CHAR or TEXT field. -- from php docs
You would need to explode the string using
explode ( string $delimiter , string $string [, int $limit ] )
This will return your data as an array
for example
foreach($data AS $post_id => $details) {
$string .= "|||$post_id||$details"
}
then to get your data back out of string
$newArray = explode('|||', $string);
foreach($newArray AS $key=>$val){
$holding = explode('||', $val);
$finalArray[$holding[0]] = $val;
}
Now you will have an array with key being the id and val being the details for each of the items in the string.
EDIT:
Or use serialize and unserialize like Brombomb suggested.
If I understand your question...
$temp = explode('-pid-', $string);
array_shift($temp);
foreach ($temp as $item) {
list($post_id, $value) = explode('-', $item);
$data[$post_id] = $value;
}
json_encode and associated json_decode may be a better option for "stringifying" your data in the first place. However, there may be a legitimate reason for doing it the way you've chosen to do it.
I'm getting
illegal offset type
error for every iteration of this code. Here's the code :
$s = array();
for($i = 0; $i < 20; $i++){
$source = $xml->entry[$i]->source;
$s[$source] += 1;
}
print_r($s)
Illegal offset type errors occur when you attempt to access an array index using an object or an array as the index key.
Example:
$x = new stdClass();
$arr = array();
echo $arr[$x];
//illegal offset type
Your $xml array contains an object or array at $xml->entry[$i]->source for some value of $i, and when you try to use that as an index key for $s, you get that warning. You'll have to make sure $xml contains what you want it to and that you're accessing it correctly.
Use trim($source) before $s[$source].
check $xml->entry[$i] exists and is an object
before trying to get a property of it
if(isset($xml->entry[$i]) && is_object($xml->entry[$i])){
$source = $xml->entry[$i]->source;
$s[$source] += 1;
}
or $source might not be a legal array offset but an array, object, resource or possibly null
There are probably less than 20 entries in your xml.
change the code to this
for ($i=0;$i< sizeof($xml->entry); $i++)
...
I had a similar problem. As I got a Character from my XML child I had to convert it first to a String (or Integer, if you expect one). The following shows how I solved the problem.
foreach($xml->children() as $newInstr){
$iInstrument = new Instrument($newInstr['id'],$newInstr->Naam,$newInstr->Key);
$arrInstruments->offsetSet((String)$iInstrument->getID(), $iInstrument);
}