Delete array element in PHP

1

I have tried multiple codes in PHP to remove an element from an array of strings by their name. There are already two days of infinite searches on the web, without any solution.

The string json:

["stringNumero1","stringNumero2","stringNumero3","stringNumero4","stringNumero5"]

The PHP code:

$index = array_search("stringNumero3", $jsonDecodificado);
if($index !== FALSE){
  unset($jsonDecodificado[$index]);
}
echo json_encode($jsonDecodificado);

Result in:

{0:"stringNumero1",1:"stringNumero2",2:"stringNumero3",3:"stringNumero4",4:"stringNumero5}

PS: The variable $jsondecodificado has as value json_decode(file_get_contents('rutaAlJson'), true)

Later I tried removing the second parameter true of json_decode() but it still did not give the expected result, the removal of the string "stringNumero3" within the array of strings.

Thanks for your answers.

    
asked by Rodrigo Salas 15.09.2017 в 21:54
source

3 answers

1

When you use unset the fix key is lost, which causes the keys to no longer be consecutive and json_encode converts it into an object. What you can do is change unset by array_splice , like this:

array_splice($jsonDecodificado, $index, 1);

Since array_splice changes the keys of the array, it returns to look like an array of continuous numeric indexes and so json_encode keeps it as normal array

    
answered by 16.09.2017 в 00:12
0

Do a var_dump($jsonDecodificado) immediately after json_decode(file_get_contents('rutaAlJson') , try this simulating your file and it works correctly:

<?php
$txt='["stringNumero1","stringNumero2","stringNumero3","stringNumero4","stringNumero5"]';
$jsonDecodificado = json_decode($txt, true);
echo "ANTES";
var_dump($jsonDecodificado);
echo json_encode($jsonDecodificado);

$index = array_search("stringNumero3", $jsonDecodificado);
if($index !== FALSE){
    //unset($jsonDecodificado[$index]);
    array_splice($jsonDecodificado, $index, true);
}
echo "<br><br>DESPUES";
var_dump($jsonDecodificado);
echo json_encode($jsonDecodificado);
?>

    
answered by 15.09.2017 в 22:30
0

You can use array_values like this:

echo json_encode(array_values($jsonDecodificado));

That way you keep using unset without problem, you can also keep the original array without any alteration of the order of its indices.

    
answered by 16.09.2017 в 20:31