Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cleaning up PHP arrays into one [closed]

Tags:

arrays

php

array(1) {
  [0] => string(18) "AnotherTestSnippet"
}
array(1) {
  [0] => string(17) "Test Code Snippet"
}
array(1) {
  [0] => string(18) "AnotherTestSnippet"
}
array(1) {
  [0] => string(17) "Test Code Snippet"
}

How to convert the above array into this format using PHP?

array("AnotherTestSnippet","Test Code Snippet")

That is cleaning up and removing the duplicates. I have tried array_unique and and in_array but it does not work. Thanks.

like image 678
Emerson Maningo Avatar asked Nov 28 '12 09:11

Emerson Maningo


Video Answer


2 Answers

Let's call your arrays $array1 through $array4. Here is the solution:

$cleanArray = array_unique(array_merge($array1, $array2, $array3, $array4));

EDIT:

Now that I know you are starting with a single, multi-dimensional array, this is not the correct answer. The correct answer is the for loop given by Dainis Abols.

like image 106
davidethell Avatar answered Sep 25 '22 14:09

davidethell


Just do a loop and save only your unique enries:

<?php
$array = array (
    array( "AnotherTestSnippet" ),
    array( "Test Code Snippet" ),
    array( "AnotherTestSnippet" ),
    array( "Test Code Snippet" )
);

$new_array = array();

foreach ( $array as $value )
{
    if( !in_array( $value[0], $new_array) ) $new_array[] = $value[0];
}

Output:

Array
(
    [0] => AnotherTestSnippet
    [1] => Test Code Snippet
)
like image 35
Peon Avatar answered Sep 21 '22 14:09

Peon