array to string conversion in php 7 code example

Example 1: Notice: Array to string conversion php

// Use json_encode to collapse the array to json string:
$stuff = array(1,2,3);
print json_encode($stuff);   //Prints [1,2,3]

Example 2: Notice: Array to string conversion php

$stuff = array(1,2,3);
print_r($stuff);
$stuff = array(3,4,5);
var_dump($stuff);

Example 3: Convert an Array to a String in PHP

phpCopy<?php
   $array = ["Lili", "Rose", "Jasmine", "Daisy"];
   $JsonObject = json_encode($array);
   echo "The array is converted to the Json string.";
   echo "\n"; 
   echo"The Json string is $JsonObject";
?>

Example 4: array to string conversion in php

function subArraysToString($ar, $sep = ', ') {
    $str = '';
    foreach ($ar as $val) {
        $str .= implode($sep, $val);
        $str .= $sep; // add separator between sub-arrays
    }
    $str = rtrim($str, $sep); // remove last separator
    return $str;
}

// $food array from example above
echo subArraysToString($food);
// apple, raspberry, pear, banana, peas, carrots, cabbage, wheat, rice, oats

Example 5: Notice: Array to string conversion php

// Joining all the cells in the array together:
<?php
    $stuff = array(1,2,3);
    print implode(", ", $stuff);    //prints 1, 2, 3
    print join(',', $stuff);        //prints 1, 2, 3
?>

Example 6: Notice: Array to string conversion php

// suppress the Notices:
error_reporting(0);
print(array(1,2,3));    //Prints 'Array' without a Notice.

Tags:

Php Example