0

Here is the situation: There are thousand of data. But not all of that are unique. The first foreach loop is unique. So, I am putting the size in a Array . Next loop might have same size. So, I am checking the size of a variable. If the size found in the Array , that means its not unique otherwise the size of that variable would be in the Array. The problem is I'm getting common and unique (both) size in the Array.

PHP Code:

$counter = array();
foreach ($result_all as $data){
    $message =  $data['msg'];
    $size_of_message = strlen($message);

    if(contains($message,$chittagong)){
       if(empty($counter)){
           $counter[] = $size_of_message;
       }else{
           foreach($counter as $a) {
               if ($size_of_message !== $a)
                   $counter[] = $size_of_message;
           }
       }
    }
}

Result:

Array
(
    [0] => 153
    [1] => 122
    [2] => 165
    [3] => 165
)

The result I am expecting:

Array
(
    [0] => 153
    [1] => 122
    [2] => 165
)
Niraj Kaushal
  • 1,452
  • 2
  • 13
  • 20

4 Answers4

0

You can easily use the native function array_unique

$array = [0=>153, 1=>122, 2=>165, 3=>165];
$array_unique = array_unique($array);
print_r($array_unique);
executable
  • 3,365
  • 6
  • 24
  • 52
0

Try

$counter = array();
foreach ($result_all as $data){
    $message =  $data['msg'];
    $size_of_message = strlen($message);
    if(contains($message,$chittagong)){
       if(empty($counter)){
           $counter[] = $size_of_message;
       }
       if(!empty($counter)){
           foreach($counter as $a) {
               if ($size_of_message !== $a)
                   $counter[] = $size_of_message;
           }
       }
    }
}

or use Array Unique after foreach

Sergey B.
  • 83
  • 1
  • 7
0

Maybe using array keys unicity is an idea :

$result = array();
foreach ($result_all as $data){
    $result[strlen($data['msg'])] = true;
}
$result = array_keys($result);
Séverin
  • 137
  • 1
  • 6
0

The problem lies here:

           foreach($counter as $a) {
               if ($size_of_message !== $a)
                   $counter[] = $size_of_message;
           }

You are comparing $size_of_message with every existing element, and for most of them if statement will return true, adding new element to counter. And you want to add it only if no element matches it. So you need to use in_array() function instead of foreach:

if (!in_array($size_of_message, $counter) {
  $counter[] = $size_of_message;
}

In this case you also don't need to check if array is empty.

Jakupov
  • 1,656
  • 2
  • 11
  • 14