Braydon Harris Braydon Harris - 1 year ago 126
PHP Question

PHP json array to delete a line in JSON file

Having a bit of an issue with some PHP code. I have an contacts list angular app to add and remove contacts. I have the add part done but the delete is giving me some grief. On ng-click I'm sending data with a $http request to remove a specific line in a JSON file. It's sending the data fine but I think something is wrong with my php...


$jsonString = file_get_contents("contacts.json");
$contactData = json_decode($jsonString, true);

$getArray = array(
"firstname" => $_POST['firstname'],
"lastname" => $_POST['lastname'],
"number" => $_POST['number'],
"hobbies" => $_POST['hobbies']

foreach ($contactData as $key => $value) {
if($value->number == $getArray) {

$json = json_encode($contactData, JSON_PRETTY_PRINT);
//Add to JSON contents
file_put_contents("contacts.json", $json);


$scope.deleteRow = function(contact){
//var index = $scope.number.indexOf(item);
method : 'POST',
url : 'delete.php',
data : $.param(contact),
headers : {'Content-Type': 'application/x-www-form-urlencoded'}


<button type="button" class="btn btn-default" aria-label="Bold" ng-click="deleteRow(contact)">

Any help would be greatly appreciated

Answer Source

Because json_decode is being called with assc==true the returning array is associative, and you should use $value['number'] instead of $value->number

An corrected code with the array_filter function for brevity:

$jsonString = file_get_contents("contacts.json");
$contactData = json_decode($jsonString, true);
$contactData = array_filter($contactData, function ($v) {return $v['number']!=$_POST['number'];});
$json = json_encode($contactData, JSON_PRETTY_PRINT);
file_put_contents("contacts.json", $json);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download