Kirakos
Kirakos

Reputation: 3

Remove an Item from Array in PHP?

I am pulling tables from a database and I'm trying to keep the userdata table from being included in the array that is eventually sent to my application. I've tried using array_diff and unset, but I haven't had any luck with it. As tables can be added, the userdata one won't always be in the same position.

The array when I check on JSONlint.com appears like this:

[{"table_name": "OSA"
}, {
    "table_name": "OSB"
}, {
    "table_name": "userdata"
}]

code in PHP file:

    $tables = array();

    while ($row = mysqli_fetch_array($result)){
    array_push($tables, array("table_name"=>$row[0]));

    }

    $remove= array({"table_name": "userdata"});
    $result = array_diff($tables, $remove);

    echo json_encode($result);

Upvotes: 0

Views: 50

Answers (1)

AbraCadaver
AbraCadaver

Reputation: 78994

The optimal way would probably be to exclude it in the query:

SELECT column FROM table WHERE column <> 'userdata'

Or, just don't add it to the array:

while($row = mysqli_fetch_array($result)) {
    if($row[0] != 'userdata') {
        $tables[] = array('table_name' => $row[0]);
    }
}

Your array_push should work fine but I prefer the above.

But to answer the unset question. Just get the table_data column values, search for userdata and unset that key:

unset($tables[array_search('userdata', array_column($tables, 'table_name'))]);

Upvotes: 2

Related Questions