Php вывод строки из массива

How to cast array elements to strings in PHP?

(each object has a __toString() -method) How can I cast all array elements to string so that array $a contains no more objects but their string representation? Is there a one-liner or do I have to manually loop through the array?

@RohitSuthar : your linked answer creates an array out of a string. This question was about converting an array of objects to an array of their string representation.

7 Answers 7

$a = array_map('strval', $a); // strval is a callback function 

Can also be called like return array_map(fn ($item) => strval($item), $items); if you’d rather not reference the function ‘strval’ as a string.

Alix Axel has the nicest answer. You can also apply anything to the array though with array_map like.

//All your objects to string. $a = array_map(function($o), $a); //All your objects to string with exclamation marks. $a = array_map(function($o), $a); 
$array = array('lastname', 'email', 'phone'); $comma_separated = implode(",", $array); echo $comma_separated; // lastname,email,phone 

No, because my array consists of objects, not strings. And the result should be an array and not an imploded string.

Not tested, but something like this should do it?

foreach($a as $key => $value) < $new_arr[$key]=$value->__toString(); > $a=$new_arr; 

Yes, and as I suggested in the comment to Alix’s post I would have offered his solution had I have known about it.

I can’t test it right now, but can you check what happens when you implode() such an array? The _toString should be invoked.

@Gordon: It’ll merge all the strings in one though, I think the OP wants to keep the __toString() generated strings in the corresponding array elements.

$str1 = "pankaj"; $str2 = array("sam",'pankaj',"hello"); function Search($x ,$y) < $search = $x; $arr = $y; foreach($y as $key =>$value)< $str = array_search($x, $y); if($str == $key)< echo $key ."=>".$value; echo "
".gettype($value); > > > Search($str1 ,$str2);

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

Читайте также:  What is binary file in java

Is there any reason why you can’t do the following?

$a = array( (string) $objA, (string) $objB, ); 

Yes, because actually I don’t know how many elements there are in the array. The example above was just reduced to two elements to make it more clear.

This question is in a collective: a subcommunity defined by tags with relevant content and experts.

Источник

Converting array to string and then back in PHP

How can I convert this array into a string in PHP and back from string into an array. This is kind of a requirement. Could someone please advice on how this can be acheived.

4 Answers 4

You can convert any PHP data-type but resources into a string by serializing it:

And back into it’s original form by unserializing it again:

A serialized array is in string form. It can be converted into an array again by unserializing it.

The same does work with json_encode / — _decode for your array as well:

$string = json_encode($array); $array = json_decode($string); 

Note the difference between using serialize/unserialize vs imlpode/explode is that the former will work regardless of the contents of the values — with the example provided by Alex, the method will fail if one of the valuse contains a space

use the function implode(separator,array) which return a string from the elements of an array.

and then the function explode ( string $delimiter , string $string [, int $limit ] ) to revert it back to an array

$array_as_string = implode(" ",$userarray); $new_array = explode(" ",$array_as_string); 
$userarray = array('UserName' => $username, 'UserId' => $userId, 'UserPicURL' => $userPicURL); $string = json_encode($userarray); $backtoarray = json_decode($string); 
$userarray = array('UserName' => $username, 'UserId' => $userId, 'UserPicURL' => $userPicURL); $string = serialize($userarray); $backtoarray = unserialize($string); 

The first one uses XML storage, and the second uses JSON.

Читайте также:  Api php для чайников

Источник

PHP Implode – Convert Array to String with Join

Kolade Chris

Kolade Chris

PHP Implode – Convert Array to String with Join

In PHP, the implode() function is a built-in function that takes an array and converts it to a string. implode() doesn’t modify the original array.

It doesn’t matter whether the array is an indexed or associative array. Once you pass in the array to implode() , it joins all the values to a string.

PHP implode() Syntax

implode() takes in two values as parameters – the separator and the array you want to convert to a string.

The separator could be any character or an empty string. It is valid as long as you specify it in quotes. If you don’t pass in the separator, implode() still works. The array on the other hand could be an associative array or an indexed array.

NB: implode() doesn’t work with nested arrays.

The full syntax of an implode() looks like this:

In the syntax above, an empty space (» «) is the separator, and $array is the array.

Examples of Implode with an Indexed Array

In PHP, an indexed array is what it sounds like – each value in the array has an index automatically assigned to it. You can also assign the indexes if you want.

Below is an example of how implode() works with an indexed array:

ss1-2

Note that I did not pass in a separator and implode() still works fine.
In the example below, I passed in an empty space, comma, and hyphen as separators:

"."
"; echo $newLangsComma."
"."
"; echo $newLangsHyphen ."
"; ?>

ss2-2

You can see it’s better to specify a separator so you can see the values well.

Читайте также:  Javascript arrays with string keys

Examples of Implode with an Associative Array

You define a named index with an associative array. Let’s see how implode() works with associative arrays.

 "Kolade", 'last_name' => "Chris", 'likes' => "football and Pro-wrestling", 'email' => "kolade@gmail.com", ]; //That's not my email. Don't bother sending me a message. $newPerson = implode(" ", $person); echo $newPerson."
"; ?>

ss3-2

You can see the indexes were not printed. To print the indexes too, you need to attach the array to the array_keys() method while printing the array:

 "Kolade", 'last_name' => "Chris", 'likes' => "football and Pro-wrestling", 'email' => "kolade@gmail.com", ]; // That’s not my email. Don't bother sending me a message. $newPersonValues = implode(", ", $person)."
"; $newPersonKeys = implode(", ", array_keys($person)); echo $newPersonKeys."
"; echo $newPersonValues; ?>

ss4-2

To prove that the original array is never modified, I’ll print the array alongside the imploded variables:

 "Kolade", 'last_name' => "Chris", 'likes' => "football and Pro-wrestling", 'email' => "kolade@gmail.com", ]; // That's not my email. Don't bother sending me a message. $newPersonValues = implode(", ", $person)."
"; $newPersonKeys = implode(", ", array_keys($person)); echo $newPersonKeys."
"; echo $newPersonValues."
"; print_r($person); ?>

You can use the PHP View Chrome extension to format your printed array so it can look better:

phpViewer

Final Thoughts

In this article, you learned about the implode() function in PHP and how it works. We looked at how the implode() function works with both indexed and associative arrays, too, with examples.

Don’t forget that implode() doesn’t work with nested arrays (multidimensional arrays). In fact, I can prove it:

ss6-2

It doesn’t work that way because implode() only works with flat arrays ( [ ] ) instead of multidimensional arrays ( [ [ ] ] ). Implode looks at the first array, and once it sees that the first array has many arrays in it, it throws an error.

Источник

Оцените статью