How to convert array to a string using methods other than JSON? - php

What is a function in PHP used to convert array to string, other than using JSON?
I know there is a function that directly does like JSON. I just don't remember.

serialize() is the function you are looking for. It will return a string representation of its input array or object in a PHP-specific internal format. The string may be converted back to its original form with unserialize().
But beware, that not all objects are serializable, or some may be only partially serializable and unable to be completely restored with unserialize().
$array = array(1,2,3,'foo');
echo serialize($array);
// Prints
a:4:{i:0;i:1;i:1;i:2;i:2;i:3;i:3;s:3:"foo";}

Use the implode() function:
$array = array('lastname', 'email', 'phone');
$comma_separated = implode(",", $array);
echo $comma_separated; // lastname,email,phone

readable output!
echo json_encode($array); //outputs---> "name1":"value1", "name2":"value2", ...
OR
echo print_r($array, true);

You are looking for serialize(). Here is an example:
$array = array('foo', 'bar');
//Array to String
$string = serialize($array);
//String to array
$array = unserialize($string);

Another good alternative is http_build_query
$data = array('foo'=>'bar',
'baz'=>'boom',
'cow'=>'milk',
'php'=>'hypertext processor');
echo http_build_query($data) . "\n";
echo http_build_query($data, '', '&');
Will print
foo=bar&baz=boom&cow=milk&php=hypertext+processor
foo=bar&baz=boom&cow=milk&php=hypertext+processor
More info here http://php.net/manual/en/function.http-build-query.php

use php implode() or serialize()

Display array in beautiful way:
function arrayDisplay($input)
{
return implode(
', ',
array_map(
function ($v, $k) {
return sprintf("%s => '%s'", $k, $v);
},
$input,
array_keys($input)
)
);
}
$arr = array('foo'=>'bar',
'baz'=>'boom',
'cow'=>'milk',
'php'=>'hypertext processor');
echo arrayDisplay($arr);
Displays:
foo => 'bar', baz => 'boom', cow => 'milk', php => 'hypertext processor'

There are different ways to do this some of them has given.
implode(), join(), var_export(), print_r(), serialize(), json_encode()exc... You can also write your own function without these:
A For() loop is very useful. You can add your array's value to another variable like this:
<?php
$dizi=array('mother','father','child'); //This is array
$sayi=count($dizi);
for ($i=0; $i<$sayi; $i++) {
$dizin.=("'$dizi[$i]',"); //Now it is string...
}
echo substr($dizin,0,-1); //Write it like string :D
?>
In this code we added $dizi's values and comma to $dizin:
$dizin.=("'$dizi[$i]',");
Now
$dizin = 'mother', 'father', 'child',
It's a string, but it has an extra comma :)
And then we deleted the last comma, substr($dizin, 0, -1);
Output:
'mother','father','child'

Related

How to convert a certain type of string into an array with keys in php?

I have a string of this type:
string(11) "2=OK, 3=OK"
from a text file. But I would like to convert it into an array of keys this type :
array (
[2] => Ok
[3] => Ok
)
I was wondering how we could do that in PHP.
Note:- I normally use explode() and str_split() for the conversions string into array but in this case I don't know how to do it.
use explode(), foreach() along with trim()
<?php
$string = "2=OK, 3=OK" ;
$array = explode(',',$string);
$finalArray = array();
foreach($array as $arr){
$explodedString = explode('=',trim($arr));
$finalArray[$explodedString[0]] = $explodedString[1];
}
print_r($finalArray);
https://3v4l.org/ZsNY8
Explode the string by ',' symbol. You will get an array like ['2=OK', ' 3=OK']
Using foreach trim and explode each element by '=' symbol
You can use default file reading code and traverse it to achieve what you want,
$temp = [];
if ($fh = fopen('demo.txt', 'r')) {
while (!feof($fh)) {
$temp[] = fgets($fh);
}
fclose($fh);
}
array_walk($temp, function($item) use(&$r){ // & to change in address
$r = array_map('trim',explode(',', $item)); // `,` explode
array_walk($r, function(&$item1){
$item1 = explode("=",$item1); // `=` explode
});
});
$r = array_column($r,1,0);
print_r($r);
array_walk — Apply a user supplied function to every member of an array
array_map — Applies the callback to the elements of the given arrays
explode — Split a string by a string
Demo.
You can use preg_match_all along with array_combine, str_word_count
$string = "2=OK, 3=OK" ;
preg_match_all('!\d+!', $string, $matches);
$res = array_combine($matches[0], str_word_count($string, 1));
Output
echo '<pre>';
print_r($res);
Array
(
[2] => OK
[3] => OK
)
LIVE DEMO

How can add in data of "file_put_contents" an array and a variable?

i would to use file_put_contents($filename, $data) but i have to add a bidimensional array and a variable:
$array= array(
array("a","a"),
array("b","b")
);
$variable= 1;
How can i add them in $data ?
Is possible to do this by not adding both in a string ?
Thanks a lot and sorry for my english
$newArray = ['array' => $array, 'variable' => $variable];
file_put_contents($filename, var_export($newArray, true));
$data should be a string, you need to convert array to string.
var_export would outputs or returns a parsable string representation of a variable.

How to remove square bracket from an array?

I have an array..let say:
$array = [$a,$b,$c,$d];
How I can remove [ and ]?
The expected result would be:
$a,$b,$c,$d
I used some array function e.g array_slice but it does not fill my requirement. Any ideas?
Note: I need to pass all array elements to function as argument.
e.g: function example($a,$b,$c)
it sounds like you're after a string representation of the array, try using join() or implode() like this:
<?php
$array = [$a,$b,$c,$d];
$str = join(",", $array); // OR $str = implode(",", $array);
echo $str;
EDIT
after reading your question a little more carefully, you're trying to pass the array into a function call, to do that you need to use call_user_func_array():
<?php
function function_name($p1, $p2, $p3, $p4){
//do something here
}
$array = [$a,$b,$c,$d];
call_user_func_array('function_name', $array);

How to get an array from string, containing an array?

Is it possible to using a regular expression, or otherwise create a function that will convert a string containing the php array of any form, in the real array, which can operate?
For Example:
$str = "array(1, array(2), array('key' => 'value'))";
$arr = stringArrayToArray($str);
Maybe there is already such an implementation of task?
Or do not bother, but simply to use eval()?
$arr = eval("return $str;");
You can try explode() function.
Try it.
<?php
$str = "do you love me";
$arr = explode(' ', $str);
print_r($arr);
?>
You can just replace the array( with a [ and ) with ]
as shown below:
$str = "array(1, array(2), array('key' => 'value'))";
$str = str_replace(" ","",str_replace(",","[",$str));
$str = str_replace(")","",str_replace("array(","[",$str));
echo $str;
$arr = explode("[",$str);
var_dump($arr);
?>
this the best I could get.

array_map with str_replace

Is it possible to use array_map in conjunction with str_replace without calling another function to do the str_replace?
For example:
array_map(str_replace(' ', '-', XXXXX), $myArr);
There is no need for array_map. From the docs: "If subject is an array, then the search and replace is performed with every entry of subject, and the return value is an array as well."
No, it's not possible. Though, if you are using PHP 5.3, you can do something like this:
$data = array('foo bar baz');
$data = array_map(function($value) { return str_replace('bar', 'xxx', $value); }, $data);
print_r($data);
Output:
Array
(
[0] => foo xxx baz
)
Sure it's possible, you just have to give array_map() the correct input for the callback function.
array_map(
'str_replace', // callback function (str_replace)
array_fill(0, $num, ' '), // first argument ($search)
array_fill(0, $num, '-'), // second argument ($replace)
$myArr // third argument ($subject)
);
But for the particular example in the question, as chiborg said, there is no need. str_replace() will happily work on an array of strings.
str_replace(' ', '-', $myArr);
Might be important to note that if the array being used in str_replace is multi-dimensional, str_replace won't work.
Though this doesn't directly answer the question of using array_map w/out calling an extra function, this function may still be useful in place of str_replace in array_map's first parameter if deciding that you need to use array_map and string replacement on multi-dimensional arrays. It behaves the same as using str_replace:
function md_str_replace($find, $replace, $array) {
/* Same result as using str_replace on an array, but does so recursively for multi-dimensional arrays */
if (!is_array($array)) {
/* Used ireplace so that searches can be case insensitive */
return str_ireplace($find, $replace, $array);
}
$newArray = array();
foreach ($array as $key => $value) {
$newArray[$key] = md_str_replace($find, $replace, $value);
}
return $newArray;
}

Categories