Marko
Marko

Reputation: 91

Create an array from arrays that holds data

I am trying to create an array that will hold the only array that contains values.

Code below works well, but I get trouble if for ex, $array2 (but can array1 or array3) doesn't contain any value. In that case, I need to merge only array1 and array3.

$array3 = array_filter( array_map( function( $term ) {
    if ( ! $term = \Softing\Term::get( $term ) ) {
        return false;
    }

    return [
        'link' => $term->get_link(),
        'name' => $term->get_name(),
        'color' => $term->get_color(), 
        ]; 


}, $terms ) );


$formatted_terms[] = array_merge($array1, $array2, $array3);

Each if three arrays are formed on the same way as $array3, but some of them could be empty, no values. Those Arrays I dont want to merge. Want to create array only from arrays that holds value.

What is the easiest way to accomplish this.

I tried using

$formatted_terms[] = array_merge((array)$array1, (array)$array2, (array)$array3);

Any advice ?

Upvotes: 0

Views: 73

Answers (3)

Boopathi D
Boopathi D

Reputation: 377

Check the array if it has values before merging,

$array1=!empty($array1) && is_array($array1)?$array1:[];
$array2=!empty($array2) && is_array($array2)?$array2:[];
$array3=!empty($array3) && is_array($array3)?$array3:[];
$formatted_terms[] = array_merge($array1, $array2, $array3);

Upvotes: 0

Samuel Cook
Samuel Cook

Reputation: 16828

You can use array_filter() to remove empty array values. Since you have a multidimensional array, you may consider using array_map() in conjunction with array_filter().

Take the following for example:

$array1 = ['link'=>'foo', 'name'=>'bar', 'filter'=>'hello world'];

$array2 = false;

$array3 = ['link'=>'foo', 'name'=>'bar', 'filter'=>'hello world'];

$formatted_terms[] = array_merge((array)$array1, (array)$array2, (array)$array3);

$formatted_terms = array_map('array_filter',$formatted_terms);

echo '<pre>',print_r($formatted_terms),'</pre>';

https://www.php.net/manual/en/function.array-map.php

https://www.php.net/manual/en/function.array-filter.php

Upvotes: 1

spyro95
spyro95

Reputation: 146

Just check if theyre an array and if theyre not empty. If so, use array merge. If not, just do nothing.

$a_all_arrays = array($array1, $array2, $array3);
$a_merged     = array();
foreach($a_all_arrays as $arr) 
{
    if(is_array($arr) && !is_empty($arr)) 
    {
        $a_merged = array_merge($a_merged, $arr);
    }
}

Upvotes: 0

Related Questions