Home > Software design >  Uncaught TypeError: array_unique(): Argument #1 ($array) must be of type array, string given in C:\
Uncaught TypeError: array_unique(): Argument #1 ($array) must be of type array, string given in C:\

Time:07-09

I am trying to get unique values in option menu in select by using array_unique(), but it constantly gives me this error:
Fatal error: Uncaught TypeError: array_unique(): Argument #1 ($array) must be of type array, string given in C:\xampp\htdocs\ncapro\112.php:27 Stack trace: #0 C:\xampp\htdocs\ncapro\112.php(27): array_unique('on rent', 2) #1 {main} thrown in C:\xampp\htdocs\ncapro\112.php on line 27

Tell me what I am doing wrong... This is my PHP code

<label for="eventType"><b>Choose a category:</b></label>
<select id="catagOption trap"  onchange="FindCatag()">

    <?php
     $str = file_get_contents('data.json');
        $b = json_decode($str);
        $sheet2 = $b->{'sheet2'};

        foreach ($sheet2 as $value) {
          $categ = array_unique($value->{'category'}, SORT_STRING);
       ?>
    
       <option value="0" data-catag-option="<?php echo $categ ?>"><?php echo $categ ?></option>
            
      <?php  } ?>
    </select>

And this is my data.json file :

{ "sheet2": [
        {
            "category": "on rent",
            "subcategory": "some area name"
        },
        {
            "category": "on rent",
            "subcategory": "some area name"
        },
        {
            "category": "on sell",
            "subcategory": "some area name"
        },
        {
            "category": "on sell",
            "subcategory": "some area name"
        },
        {
            "category": "doctor",
            "subcategory": "some area name"
        },
        {
            "category": "doctor",
            "subcategory": "some area name"
        }, ... and much more ] }

CodePudding user response:

The error message tells you exactly what are you doing wrong.

array_unique() function takes an array as an argument, and removes duplicates from it. From php.net:

array_unique — Removes duplicate values from an array

array_unique(array $array, int $flags = SORT_STRING): array

Takes an input array and returns a new array without duplicate values.

However, you're not passing an array to this function. $value->{'category'} is a string ("on rent", "on sell" or "doctor").

What you need to do, is to make an array of all 'category' strings and then make this array unique:

$categories = array_map(
   fn($value) => $value->{'category'},
   $sheet2
);
$categories = array_unique($categories);

Then you can loop through this array and print it:

<?php foreach($categories as $category): ?>
   <option value="0" data-catag-option="<?= $category ?>"><?= $category ?></option>
<?php endforeach; ?>
  • Related