-2

I am working on a code in which I fetch a particular row from a mySQL database using php. The value that I take from the row is like "CSS, HTML, JAVASCRIPT, AJAX, BOTSTRAP,DJANGO, LAYNX,BOTSTRAP,JQUERY,AJAX" this is a single sentence/value from a row. what I want is to convert this sentence into an array and remove duplicate values and use that array further. My code goes as below.

<?php  $sql = "SELECT * FROM user_info WHERE user_id = '$user_id' ";
        $run_query = mysqli_query($con,$sql);
        $row = mysqli_fetch_array($run_query);
        $string = $row["skills_covered"];
        
  $string = array_unique(explode(",", $string));
         $count=count($string);
                  for($ib=0;$ib<$count;$ib++){
             echo "<li><a href='#' > $count |$string[$ib] </a></li>";
                  }
        
               ?> 

the output that I'm getting is

10 |CSS
10 | HTML
10 | JAVASCRIPT
10 | AJAX
10 | BOTSTRAP
10 |DJANGO
10 | LAYNX
10 |BOTSTRAP
10 |JQUERY
10 |AJAX

the output that I want is

8|CSS
8| HTML
8| JAVASCRIPT
8| AJAX
8| BOTSTRAP
8|DJANGO
8| LAYNX
8|JQUERY

Thanks in advance

2 Answers2

1

Your issue is that some of your values have spaces in them after you explode the string, so they don't compare as equal. You can avoid that by using preg_split and splitting the string on a comma which may be preceded or followed by spaces:

$skills = array_unique(preg_split('/\s*,\s*/', $string));
$count = count($skills);
foreach ($skills as $skill) {
    echo "<li><a href='#' > $count |$skill </a></li>";
}

Output:

<li><a href='#' > 8 |CSS </a></li>
<li><a href='#' > 8 |HTML </a></li>
<li><a href='#' > 8 |JAVASCRIPT </a></li>
<li><a href='#' > 8 |AJAX </a></li>
<li><a href='#' > 8 |BOTSTRAP </a></li>
<li><a href='#' > 8 |DJANGO </a></li>
<li><a href='#' > 8 |LAYNX </a></li>
<li><a href='#' > 8 |JQUERY </a></li>

Demo on 3v4l.org

Note that because array_unique returns the original keys of the array, you can't use a for loop to iterate over the values as keys with duplicate values will be missing (in your case, the for loop would fail at $ib = 7). A foreach loop works around that problem.

Nick
  • 138,499
  • 22
  • 57
  • 95
0
<?php
// String
$string = "CSS, HTML, JAVASCRIPT, AJAX, BOTSTRAP,DJANGO, LAYNX,BOTSTRAP,JQUERY,AJAX";

// Split
$explodedArray = explode(",", $string);

// Trim on whole array
$trimmedArray = array_map('trim', $explodedArray);

// Remove duplicates
$perfectArray = array_unique($trimmedArray);

// Rest
$count = count($perfectArray);
for($ib=0; $ib < $count; $ib++){
    echo "<li><a href='#'>$count | $perfectArray[$ib]</a></li>";
}