Codebrekers Codebrekers - 4 months ago 8
PHP Question

convert array into array to string is possible..?

How to convert array within array to string, that means I am having a one result set having value of country id but the result set will be in array within array.

Something like below code :

Array
(
[0] => Array
(
[country_id] => 7
)

[1] => Array
(
[country_id] => 8
)

[2] => Array
(
[country_id] => 9
)

[3] => Array
(
[country_id] => 10
)

[4] => Array
(
[country_id] => 1
)

[5] => Array
(
[country_id] => 2
)

[6] => Array
(
[country_id] => 3
)

[7] => Array
(
[country_id] => 4
)

[8] => Array
(
[country_id] => 5
)

)


I want that country list into one string like 7,8,9,10,1,2,3,4,5 but without looping..

Anyone have idea please let me know...?

Answer

You can use array_column() and implode() function to do this.

Here is how you can do it,

$values=array_column($array,"country_id");
$country_string=implode($values);

array_column() returns the values from a single column of the input, identified by the column_key(country_id).

implode() returns a string containing a string representation of all the array elements in the same order, with the glue string between each element.


implode() can have two arguments, first as glue by which you want to join the elements and second as the array of elements. If first argument is not given then default glue is ",".

Comments