[php] Convert the first element of an array to a string in PHP

I have a PHP array and want to convert it to a string.

I know I can use join or implode, but in my case array has only one item. Why do I have to use combine values in an array with only one item?

This array is the output of my PHP function which returns an array:

Array(18 => 'Something');

How do I convert this to a string?

This question is related to php arrays string object

The answer is


Since the issue of whitespace only comes up when exporting arrays, you can use the original var_export() for all other variable types. This function does the job, and, from the outside, works the same as var_export().

<?php

function var_export_min($var, $return = false) {
    if (is_array($var)) {
        $toImplode = array();
        foreach ($var as $key => $value) {
            $toImplode[] = var_export($key, true).'=>'.var_export_min($value, true);
        }
        $code = 'array('.implode(',', $toImplode).')';
        if ($return) return $code;
        else echo $code;
    } else {
        return var_export($var, $return);
    }
}

?>

http://www.php.net/manual/en/function.var-export.php#54440


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'


Convert an array to a string in PHP:

  1. Use the PHP join function like this:

    $my_array = array(4, 1, 8);
    
    print_r($my_array);
    Array
    (
        [0] => 4
        [1] => 1
        [2] => 8
    )
    
    $result_string = join(',', $my_array);
    echo $result_string;
    

    Which delimits the items in the array by comma into a string:

    4,1,8
    
  2. Or use the PHP implode function like this:

    $my_array = array(4, 1, 8);
    echo implode($my_array);
    

    Which prints:

    418
    
  3. Here is what happens if you join or implode key value pairs in a PHP array

    php> $keyvalues = array();
    
    php> $keyvalues['foo'] = "bar";
    
    php> $keyvalues['pyramid'] = "power";
    
    php> print_r($keyvalues);
    Array
    (
        [foo] => bar
        [pyramid] => power
    )
    
    php> echo join(',', $keyvalues);
    bar,power
    php> echo implode($keyvalues);
    barpower
    php>
    

Use the inbuilt function in PHP, implode(array, separator):

<?php
    $ar = array("parth","raja","nikhar");
    echo implode($ar,"/");
?>

Result: parth/raja/nikhar


You can use the reset() function, it will return the first array member.


A simple way to create a array to a PHP string array is:

<?PHP
    $array = array("firstname"=>"John", "lastname"=>"doe");
    $json = json_encode($array);
    $phpStringArray = str_replace(array("{", "}", ":"), 
                                  array("array(", "}", "=>"), $json);
    echo phpStringArray;
?>

implode or join (they're the exact same thing) would work here. Alternatively, you can just call array_pop and get the value of the only element in the array.


For completeness and simplicity sake, the following should be fine:

$str = var_export($array, true);

It does the job quite well in my case, but others seem to have issues with whitespace. In that case, the answer from ucefkh provides a workaround from a comment in the PHP manual.


If your goal is output your array to a string for debbuging: you can use the print_r() function, which receives an expression parameter (your array), and an optional boolean return parameter. Normally the function is used to echo the array, but if you set the return parameter as true, it will return the array impression.

Example:

    //We create a 2-dimension Array as an example
    $ProductsArray = array();

    $row_array['Qty'] = 20;
    $row_array['Product'] = "Cars";

    array_push($ProductsArray,$row_array);

    $row_array2['Qty'] = 30;
    $row_array2['Product'] = "Wheels";

    array_push($ProductsArray,$row_array2);

    //We save the Array impression into a variable using the print_r function
    $ArrayString = print_r($ProductsArray, 1);

    //You can echo the string
    echo $ArrayString;

    //or Log the string into a Log file
    $date = date("Y-m-d H:i:s", time());
    $LogFile = "Log.txt";
    $fh = fopen($LogFile, 'a') or die("can't open file");
    $stringData = "--".$date."\n".$ArrayString."\n";
    fwrite($fh, $stringData);
    fclose($fh);

This will be the output:

Array
(
    [0] => Array
        (
            [Qty] => 20
            [Product] => Cars
        )

    [1] => Array
        (
            [Qty] => 30
            [Product] => Wheels
        )

)

You could use print_r and html interpret it to convert it into a string with newlines like this:

$arraystring = print_r($your_array, true); 

$arraystring = '<pre>'.print_r($your_array, true).'</pre>';

Or you could mix many arrays and vars if you do this

ob_start();
print_r($var1);
print_r($arr1);
echo "blah blah";
print_r($var2);
print_r($var1);
$your_string_var = ob_get_clean();

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"
                                                      // }

Convert array to a string in PHP:

Use the PHP join function like this:

$my_array = array(4,1,8);

print_r($my_array);
Array
(
    [0] => 4
    [1] => 1
    [2] => 8
)

$result_string = join(',' , $my_array);
echo $result_string;

Which delimits the items in the array by comma into a string:

4,1,8

Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to object

How to update an "array of objects" with Firestore? how to remove json object key and value.? Cast object to interface in TypeScript Angular 4 default radio button checked by default How to use Object.values with typescript? How to map an array of objects in React How to group an array of objects by key push object into array Add property to an array of objects access key and value of object using *ngFor