php - How Can I Remove An Index From An Array and Echo It Out?

In PHP I am trying to have it so the user can insert an array of an index that they want removed and then it will echo out that array without the array that they didn't want. Right now the troublesome part of my code for the main file is

include("/opt/lampp/htdocs/upload/styles/styles.php");
if ($_SERVER['REQUEST_METHOD'] == "POST") {
//this is the content of the array that the user wants gone//
$want = $_POST['which'];
$file = fopen("/opt/lampp/htdocs/upload/styles/styles.php", "a");
if (in_array($want, $allStyles)) {
        $index = array_search($want, $allStyles);
        fwrite($file, " unset(\$allStyles[$index]);");
        fclose($file);
        echo implode(", ", $allStyles);
} else {
        echo "error";
}
}

styles.php is

<?php
$allStyles[] = 'one';
$allStyles[] = 'all';

If I insert "all" for $want it will unset the array where it contains "all" and if I do

php styles.php

in my linux terminal it will only echo out "one" but if I do this on my page on my web browser it will echo out both strings. How can I make it so it will only echo the array that wasn't asked to be removed?

Answer

Solution:

not sure if I understood your problem (or what you want to achieve) properly but, try this code:

$file='/opt/lampp/htdocs/upload/styles/styles.php';
include($file);
if(isset($_POST['which'])){
    $want=$_POST['which'];
    if(in_array($want,$allStyles)){
        $index=array_search($want,$allStyles);
        unset($allStyles[$index]);
        file_put_contents($file,$allStyles);
    }else{
        echo "error";
    }
}

You only want to change the file if $_POST['which'] is set, not on every POST action, I guess.

You just search the index (like you already did the right way) then unset it (what was wrong in your code, I guess) then you write it (file_put_contents() makes the code a bit more readable).

Last thing: I've moved the path to the file in $file in order to make it more maintainable

Source