PHP: Turn array into string? - php

I have a problem: I need to turn an array into a string and pass it to a function for debugging output.
I cannot directly output the string with print_r, I need to join it with some other strings and pass it to a function.
Google did not bring any results that display the array in a human-readable way without directly printing them. I need a string which I can pass to another function.

You can use the print_r() function like this:
$myarray = ['a', 'b', 'c'];
$string = print_r($myarray, true);
echo $string;
The optional boolean flag as second parameters makes the function return a string instead of directly sending it to the output.

print_r uses an optional parameter to set to true to return the string instead of outputting it :
$array = array('foo', 'bar', array('baz' => true, 'test' => 42));
$stringifiedArray = print_r($array, true);
/* $stringifiedArray == "
Array
(
[0] => foo
[1] => bar
[2] => Array
(
[baz] => 1
[test] => 42
)
)
"
*/
Otherwise, I can see two ways, but both are not as easily readable by a human :
json_encode :
$stringifiedArray = json_encode($array, true);
// $stringifiedArray == "["foo","bar",{"baz":true,"test":42}]"
serialize :
$stringifiedArray = serialize($array, true);
// $stringifiedArray == "a:3:{i:0;s:3:"foo";i:1;s:3:"bar";i:2;a:2:{s:3:"baz";b:1;s:4:"test";i:42;}}"

You could also try <?php implode(', ', $array); ?>

Related

Get matches from a preg_replace and use them as an array key

I want to get matches from a String and use them in a array as key to change the value in the string to the value of the array.
If it would be easier to realize, i can change the fantasy tags from %! also to whatever don't have problems in JS/jQuery. This script is for external JS Files and change some variables, which I can't Access from JS/jQuery. So I want to insert them with PHP and send them minified and compressed to the Browser.
$array = array ( 'abc' => 'Test', 'def' => 'Variable', 'ghi' => 'Change' );
$string ='This is just a %!abc!% String and i wanna %!ghi!% the %!def!%';
$string = preg_replace('%!(.*?)!%',$array[$1],$string);
echo $string;
You can use array_map with preg_quote to turn the keys of your array into regexes, and then use the values of the array as replacement strings in the array form of preg_replace:
$array = array ( 'abc' => 'Test', 'def' => 'Variable', 'ghi' => 'Change' );
$string ='This is just a %!abc!% String and i wanna %!ghi!% the %!def!%';
$regexes = array_map(function ($k) { return "/" . preg_quote("%!$k!%") . "/"; }, array_keys($array));
$string = preg_replace($regexes, $array, $string);
echo $string;
Output:
This is just a Test String and i wanna Change the Variable
Demo on 3v4l.org

Remove empty values from PHP array but keep 0

I have an array
array (size=7)
0 => string '2'
1 => string ''
2 => string ''
3 => string '0'
4 => string ''
5 => string ''
6 => string '2.5'
I used:-
array_filter()
to remove the null values and it returns
Array ( [0] => 2 [6] => 2 )
array_filter() removes null value and also '0' value.
Any builtin function is available in PHP to remove NULL values only.
Assumption: I think you want to remove NULL as well as empty-strings/values '' from your array. (What i understand from your desired output)
You have to use array_filter() with strlen()
array_filter($array,'strlen');
Output:-
https://eval.in/926585
https://eval.in/926595
https://eval.in/926602
Refrence:-
PHP: array_filter - Manual
PHP: strlen - Manual
Both 0 and '' are considered falsey in php, and so would be removed by array filter without a specific callback. The suggestion above to use 'strlen' is also wrong as it also remove an empty string which is not the same as NULL. To remove only NULL values as you asked, you can use a closure as the callback for array_filter() like this:
array_filter($array, function($v) { return !is_null($v); });
You can remove empty value and then re-index the array elements by using array_values() and array_filter() function together as such:
$arr = array("PHP", "HTML", "CSS", "", "JavaScript", null, 0);
print_r(array_values(array_filter($arr)));
Output:
Array
(
[0] => PHP
[1] => HTML
[2] => CSS
[3] => JavaScript
)
function myFilter($var){
return ($var !== NULL && $var !== FALSE && $var !== '');
}
$res = array_filter($yourArray, 'myFilter');
If you just need the numeric values you can use is_numeric as your callback
Demo
$res = array_filter($values, 'is_numeric');
In case your array could contain line feeds and you want to filter them out as well, you may want to trim values first:
$arrayItems = ["\r", "\n", "\r\n", "", " ", "0", "a"];
$newArray = array_values(array_filter(array_map('trim', $arrayItems), 'strlen'));
// Output(newArray): ["0", "a"]
//Another great snippet to remove empty items from array
$newArray = array_filter($arrayItems , function ($item) {
return !preg_match('/^\\s*$/', $item);
// filter empty lines
});
// Output(newArray): ["0", "a"]
If you face any issue with implementing the code just comment here below.
As of PHP 7.4:
$withoutNulls = array_filter($withNulls, static fn($e) => $e !== null);
Remove null values from array
$array = array("apple", "", 2, null, -5, "orange", 10, false, "");
var_dump($array);
echo "<br>";
// Filtering the array
$result = array_filter($array);
var_dump($result);
?>

Unable to recreate object from var_exported data (in PHP)

A script running on on our live server sends out data from the following line:
$log_output .= '<br>'.__LINE__.'<br>recordings_data='.var_export($recordings_data,TRUE);
Which looks like this:
recordings_data=stdClass::__set_state(array( 'RecordingLongResponse'
=> array ( 0 => stdClass::__set_state(...), 1 => stdClass::__set_state(), 2 => stdClass::__set_state(), 3 =>
stdClass::__set_state(array( 'roomStartDate' => '1321977120000',
'roomEndDate' => '1321977120000', 'recordingURL' => 'serverURL1',
'secureSignOn' => false, 'recordingId' => '1287268130290',
'creationDate' => '1321977120000', 'recordingSize' => '6765975',
'roomName' => 'Stakeholder Analysis', 'sessionId' => '1287268130229',
)), ...), ))
I'm not sure how to 'recreate' the object. I tried unserializing it:
$recording_data_ser= file_get_contents('elm-ser-data.txt'); // where I've saved everything after the '='
$recording_data = unserialize($recording_data_ser);
serialize() and unserialize() are the generally accepted methods for dumping/loading PHP objects. You can also do it with json_encode() and json_decode(). Is there a reason you want to use var_export()?
Edit: you can only unserialize() the result of serialize() - var_dump() is in a completely different format and isn't designed for importing unless you use eval().
For example:
$arr = array('foo' => 'bar');
var_export($arr);
#=> array (
#=> 'foo' => 'bar',
#=> )
echo serialize($arr);
#=> a:1:{s:3:"foo";s:3:"bar";}
echo json_encode($arr);
#=> {"foo":"bar"}
Once you have the serialized data (via serialize() or json_encode()), you can use the opposite method (unserialize() or json_decode(), respectively) to recreate the object again.
var_export() is intended to dump a data structure to a file. You then have to eval() or include() or require() that file. the serialize() format is completely different from var_export.
var_export produces valid PHP code to define a data structure, as if you'd written out the array/object definition yourself. serialize/unserialize write out in a completely different format, and they're not interchangeable.
If you call var_export() on an instance of stdClass, it attempts to export it using ::__set_state(), which, for some reason, is not implemented in stdClass.
However, casting an associative array to an object usually produces the same effect (at least, it does in my case). So I wrote an improved_var_export() function to convert instances of stdClass to (object) array () calls. If you choose to export objects of any other class, I'd advise you to implement ::__set_state() in those classes.
<?php
/**
* An implementation of var_export() that is compatible with instances
* of stdClass.
* #param mixed $variable The variable you want to export
* #param bool $return If used and set to true, improved_var_export()
* will return the variable representation instead of outputting it.
* #return mixed|null Returns the variable representation when the
* return parameter is used and evaluates to TRUE. Otherwise, this
* function will return NULL.
*/
function improved_var_export ($variable, $return = false) {
if ($variable instanceof stdClass) {
$result = '(object) '.improved_var_export(get_object_vars($variable), true);
} else if (is_array($variable)) {
$array = array ();
foreach ($variable as $key => $value) {
$array[] = var_export($key, true).' => '.improved_var_export($value, true);
}
$result = 'array ('.implode(', ', $array).')';
} else {
$result = var_export($variable, true);
}
if (!$return) {
print $result;
return null;
} else {
return $result;
}
}
// Example usage:
$obj = new stdClass;
$obj->test = 'abc';
$obj->other = 6.2;
$obj->arr = array (1, 2, 3);
improved_var_export((object) array (
'prop1' => true,
'prop2' => $obj,
'assocArray' => array (
'apple' => 'good',
'orange' => 'great'
)
));
/* Output:
(object) array ('prop1' => true, 'prop2' => (object) array ('test' => 'abc', 'other' => 6.2, 'arr' => array (0 => 1, 1 => 2, 2 => 3)), 'assocArray' => array ('apple' => 'good', 'orange' => 'great'))
*/
// Example implementation in context of OP
$export = improved_var_export($data, true);
file_put_contents(dirname(__FILE__).'/data.php', '<'.'?php return '.$export.'; ?'.'>');
// "Unserialization" (evaluation)
$import = include dirname(__FILE__).'/data.php';
?>

Convert flat array to a delimited string to be saved in the database

What is the best method for converting a PHP array into a string?
I have the variable $type which is an array of types.
$type = $_POST[type];
I want to store it as a single string in my database with each entry separated by | :
Sports|Festivals|Other
Use implode
implode("|",$type);
You can use json_encode()
<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr);
?>
Later just use json_decode() to decode the string from your DB.
Anything else is useless, JSON keeps the array relationship intact for later usage!
json_encode($data) //converts an array to JSON string
json_decode($jsonString) //converts json string to php array
WHY JSON : You can use it with most of the programming languages, string created by serialize() function of php is readable in PHP only, and you will not like to store such things in your databases specially if database is shared among applications written in different programming languages
One of the Best way:
echo print_r($array, true);
No, you don't want to store it as a single string in your database like that.
You could use serialize() but this will make your data harder to search, harder to work with, and wastes space.
You could do some other encoding as well, but it's generally prone to the same problem.
The whole reason you have a DB is so you can accomplish work like this trivially. You don't need a table to store arrays, you need a table that you can represent as an array.
Example:
id | word
1 | Sports
2 | Festivals
3 | Classes
4 | Other
You would simply select the data from the table with SQL, rather than have a table that looks like:
id | word
1 | Sports|Festivals|Classes|Other
That's not how anybody designs a schema in a relational database, it totally defeats the purpose of it.
implode():
<?php
$string = implode('|',$types);
However, Incognito is right, you probably don't want to store it that way -- it's a total waste of the relational power of your database.
If you're dead-set on serializing, you might also consider using json_encode()
This one saves KEYS & VALUES
function array2string($data){
$log_a = "";
foreach ($data as $key => $value) {
if(is_array($value)) $log_a .= "[".$key."] => (". array2string($value). ") \n";
else $log_a .= "[".$key."] => ".$value."\n";
}
return $log_a;
}
Hope it helps someone.
$data = array("asdcasdc","35353","asdca353sdc","sadcasdc","sadcasdc","asdcsdcsad");
$string_array = json_encode($data);
now you can insert this $string_array value into Database
For store associative arrays you can use serialize:
$arr = array(
'a' => 1,
'b' => 2,
'c' => 3
);
file_put_contents('stored-array.txt', serialize($arr));
And load using unserialize:
$arr = unserialize(file_get_contents('stored-array.txt'));
print_r($arr);
But if need creat dinamic .php files with array (for example config files), you can use var_export(..., true);, like this:
Save in file:
$arr = array(
'a' => 1,
'b' => 2,
'c' => 3
);
$str = preg_replace('#,(\s+|)\)#', '$1)', var_export($arr, true));
$str = '<?php' . PHP_EOL . 'return ' . $str . ';';
file_put_contents('config.php', $str);
Get array values:
$arr = include 'config.php';
print_r($arr);
You can use serialize:
$array = array('text' => 'Hello world', 'value' => 100);
$string = serialize($array); // a:2:{s:4:"text";s:11:"Hello world";s:5:"value";i:100;}
and use unserialize to convert string to array:
$string = 'a:2:{s:4:"text";s:11:"Hello world";s:5:"value";i:100;}';
$array = unserialize($string); // 'text' => 'Hello world', 'value' => 100
there are many ways ,
two best ways for this are
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr);
//ouputs as
{"a":1,"b":2,"c":3,"d":4,"e":5}
$b = array ('m' => 'monkey', 'foo' => 'bar', 'x' => array ('x', 'y', 'z'));
$results = print_r($b, true); // $results now contains output from print_r
Yet another way, PHP var_export() with short array syntax (square brackets) indented 4 spaces:
function varExport($expression, $return = true) {
$export = var_export($expression, true);
$export = preg_replace("/^([ ]*)(.*)/m", '$1$1$2', $export);
$array = preg_split("/\r\n|\n|\r/", $export);
$array = preg_replace(["/\s*array\s\($/", "/\)(,)?$/", "/\s=>\s$/"], [null, ']$1', ' => ['], $array);
$export = join(PHP_EOL, array_filter(["["] + $array));
if ((bool) $return) return $export; else echo $export;
}
Taken here.
If you have an array (like $_POST) and need to keep keys and values:
function array_to_string($array) {
foreach ($array as $a=>$b) $c[]=$a.'='.$b;
return implode(', ',$c);
}
Result like: "name=Paul, age=23, city=Chicago"

Parsing HTTP data into PHP variables

I have a reasonably large number of variables encoded in the form:
foo=bar&spam[eggs]=delicious&...
These are all in a single string (eg, $data = "foo=bar&spam[eggs]=delicious&..."). The variables are arbitrarily deeply nested -- easily four or five levels deep ("spam[eggs][bloody][vikings]=loud").
Is there an easy, reliable way to get a multi-dimensional PHP array from this? I assume PHP has a parser to do this, though I don't know if it's exposed for my use. Ideally, I could do something like:
// given $data == "foo=bar&spam[eggs]=delicious"
$arr = some_magical_function( $data );
/* arr = Array
(
[foo] => bar
[spam] => Array
(
[eggs] => delicious
)
)
*/
If your string is in URI params format, parse_str is the magic function you are looking for.
You might want to take a look at parse_str ; here's an example :
$str = "first=value&arr[]=foo+bar&arr[]=baz";
parse_str($str, $output);
echo $output['first']; // value
echo $output['arr'][0]; // foo bar
echo $output['arr'][1]; // baz
And, with your input :
$str = 'oo=bar&spam[eggs]=delicious&spam[eggs][bloody][vikings]=loud';
$output = array();
parse_str($str, $output);
var_dump($output);
You'll get this :
array
'oo' => string 'bar' (length=3)
'spam' =>
array
'eggs' =>
array
'bloody' =>
array
'vikings' => string 'loud' (length=4)
Which should be what you want ;-)
(notice the multi-level array ; and the fact that ths first spam[eggs] has been overriden by the second one, btw)
If your data comes from the request uri, use $_GET

Categories