Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

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
like image 261
Muhammad Yahya Imran Avatar asked Nov 01 '25 18:11

Muhammad Yahya Imran


2 Answers

Legacy signature (deprecated as of PHP 7.4.0, removed as of PHP 8.0.0):

implode(array $array, string $separator): string

Use this instead:

 implode(string $separator, array $array): string

source: https://www.php.net/manual/en/function.implode.php

like image 193
Thanasis Avatar answered Nov 03 '25 09:11

Thanasis


$_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.

like image 43
Dharman Avatar answered Nov 03 '25 10:11

Dharman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!