Search code examples
phparraysforeachunique

How to convert a 2-dim array of strings into 1-dim array of trimmed, unique values?


I have an array whose values are all arrays of a specific format that looks like this:

Array
(
    [0] => Array
        (
            [0] => '8227'
            [1] => ' 8138'
        )

    [1] => Array
        (
            [0] => '8227'
            [1] => ' 8138'
            [2] => ' 7785'
        )

)

and I would like to have this:

Array
(
    [0] => 8227
    [1] => 8138
    [2] => 7785
)

How can I do this ?


Solution

  • $result = array();
    foreach ($input as $sub) { // Loop outer array
      foreach ($sub as $val) { // Loop inner arrays
        $val = trim($val);
        if (!in_array($val, $result)) { // Check for duplicates
          $result[] = $val; // Add to result array
        }
      }
    }