Home > Back-end >  Is it possible to use implode() as a condition ? If not, what's the best way to check if the ar
Is it possible to use implode() as a condition ? If not, what's the best way to check if the ar

Time:09-28

I want implode an array in a loop. Sometime this array is a simple array so it works, sometime that's a multidimensional array and my script throw an error.

Is it possible to do something like that :

if (implode($array) ) {

$builded = implode($array);

}

Exemple value for $array :

$array1 = ["cat", "dog"] ;

$array2 = [
    "cat",
    "dog",
    1 => ["wolf", "lion"]
] ;
$array3 = [
    "cat",
    "dog",
     1 => []
] ;

implode() only works on $array1, with array $2 and $3 implode() legitimately give me an error : Notice: Array to string conversion in C:\Users[...]2_cms_php_functions\class_json.php on line 153

I know that's possible with some function returning false like if (file_get_contents($file)). If not possible, what's the best way checking if an array can be imploded ?

I'm aware about if (count($array) == count($array, COUNT_RECURSIVE)) and others solutions checking if the array is multidimensional but that's not working with empty sub array (and I often got the case).

CodePudding user response:

For this, you can write a simple function to check if the array is recursive or not. If it ain't , function returns true, else false indicating whether it can be imploded or not.

<?php

function canImplode($data){
    foreach($data as $val){
        if(is_object( $val ) || is_array( $val )) return false;
    }
    return true;
}

if(canImplode($array)){
  $builded = implode($array);
}
  • Related