Search code examples
phpphp-8

"TypeError: implode(): Argument #2 ($array) must be of type ?array, string given" in PHP 8


<div class="form-group col-md-8" id="my" style="display: none;">
    <label>Choose Vpn Server</label>
    <div class="row">
        <?php
            $sqlUrl4 = "SELECT * FROM vpn_networks";
            $result4 = myQuery($sqlUrl4);

            while ($row4 = myFetchArray($result4)) {
        ?>
        <div class="col-sm-4 text-center">
            <label>
                <input type="checkbox" name="vpn_network[]" value="<?php echo $row4['id'];?>" id="iptv" />
                <?php echo $row4['title'];?>
            </label>
        </div>
        <?php
                    }
                ?>
    </div>
</div>
$vpn1 =implode(',', $_POST['vpn_network']?? '');

Error:

Fatal error: Uncaught TypeError: implode(): Argument #2 ($array) must
be of type ?array, string given in
C:\xampp\htdocs\ideology\partnerprocess.php:22 Stack trace: #0
C:\xampp\htdocs\ideology\partnerprocess.php(22): implode(',', '') #1
{main} thrown in C:\xampp\htdocs\ideology\partnerprocess.php on line
22

Solution

  • $_POST['vpn_network'] ?? '' means that the value can either be the array that you submitted or a string. It would make more sense to have $_POST['vpn_network'] ?? [].

    You really should not trust the values submitted in the form. Check each of your assumptions. If you expect an array than check if it is an array.

    $vpn_network = isset($_POST['vpn_network']) && is_array($_POST['vpn_network']) ? $_POST['vpn_network'] : [];
    $vpn1 =implode(',', $vpn_network);
    

    You could also use the filter extension. It offers a number of filters that can validate the data coming from forms.