Convert the first element of an array to a string in PHP
Is there any other way to convert that array into string ?
Yes there is. serialize()
. It can convert various data types (including object and arrays) into a string representation which you can unserialize()
at a later time. Serializing an associative array such as Array(18 => 'Somthing')
will preserve both keys and values:
<?php
$a = array(18 => 'Something');
echo serialize($a); // a:1:{i:18;s:9:"Something";}
var_dump(unserialize('a:1:{i:18;s:9:"Something";}')); // array(1) {
// [18]=>
// string(9) "Something"
// }
Is there any other way to convert that array into string ?
You don't want to convert the array to a string, you want to get the value of the array's sole element, if I read it correctly.
<?php
$foo = array( 18 => 'Something' );
$value = array_shift( $foo );
echo $value; // 'Something'.
?>
Using array_shift you don't have to worry about the index.
EDIT: Mind you, array_shift is not the only function that will return a single value. array_pop( ), current( ), end( ), reset( ), they will all return that one single element. All of the posted solutions work. Using array shift though, you can be sure that you'll only ever get the first value of the array, even when there are multiple.