Inserting and replacing values to multidimensional array when it exists or not

p3ace asked
php arrays multidimensional-array
via

I am trying to replace the initial values of a multidimensional session array everytime the user submits a form. It must not have a duplicate in the array. I’m having trouble inserting user input value per form submission to specific row and column of the session array.

All codes are in one php file.

<?php 
    session_start();
    $_SESSION['numbers'] = array(
        array(0,0,0,0,0), //row1
        array(0,0,0,0,0), //row2
        array(0,0,0,0,0), //row3
        array(0,0,0,0,0), //row4
        array(0,0,0,0,0) //row5
    );
?>

<?php
    if (isset($_POST["num"]) && !empty($_POST["num"])){
        $userInput = $_POST["num"];
        if(!in_array($userInput, $_SESSION['numbers'])){
            echo "<script>alert('does not exist')</script>";
            //$_SESSION['numbers'] [] = $userInput;
        }else{
            echo "<script>alert('exists')</script>";
            //don't add to array
        }
    }

        echo "<table border = 1>";
        for($row = 0; $row < sizeof($_SESSION['numbers']); $row++){
            echo "<tr>";
            for($col = 0; $col < sizeof($_SESSION['numbers']); $col++){     
                echo "<td>".$_SESSION['numbers'][$row][$col]."</td>";
            }
            echo "</tr>";
        }
        echo "</table>";    

?>

However, if I do

$_SESSION['numbers'] = $userInput;

it replaces the entire multidimensional array with just 1 value instead of inserting it to the specific row and column of the nested array.

If input is, lets say 1 and the user hits the submit button, the output I get in table for each row and column is just 1

I can’t properly insert it in a specific row<tr> and column<td>.

It’s easy if it’s one dimensional array but I don’t know how to do it in multidimensional arrays nested. Please help.

Thank you.


Answer
via

Each of the rows has numeric index in your array; e.g., row 1 is index 0, row 2 is index 1, etc. What you need to do is have the form submitted with a specific row number, that way you’ll know where it needs to be inserted. With that in place, the following will do the trick for you.

Then, you can iterate the rows and add it in if it doesn’t already exist.

foreach($_SESSION['numbers'] as $_row_index => &$_row) {
    if($_row_index == (int)$_POST['row_index']) {
        if (!in_array((int)$_POST['num'], $_row, true)) {
            $_row[] = (int)$_POST['num']; // Add the num.
        }
    }
}
Share This
Posted in: