2

Here is a dummy example:

$errors = [];
for ($i = 0; $i < 3; $i++) {
    $errors[] = [
        'id' => $i
    ];
}

$errors[] = [
    'id' => 0
];

for ($i = 3; $i < 5; $i++) {
    $errors[] = [
        'id' => $i
    ];
}


var_dump($errors);
echo "<br/>";
var_dump(array_unique($errors, SORT_REGULAR));

The output above is:

array(6) { 
    [0]=> array(1) { ["id"]=> int(0) } 
    [1]=> array(1) { ["id"]=> int(1) } 
    [2]=> array(1) { ["id"]=> int(2) } 
    [3]=> array(1) { ["id"]=> int(0) } 
    [4]=> array(1) { ["id"]=> int(3) } 
    [5]=> array(1) { ["id"]=> int(4) } 
} 

array(5) { 
    [0]=> array(1) { ["id"]=> int(0) } 
    [1]=> array(1) { ["id"]=> int(1) } 
    [2]=> array(1) { ["id"]=> int(2) } 
    [4]=> array(1) { ["id"]=> int(3) } 
    [5]=> array(1) { ["id"]=> int(4) } 
}

As you can see, the second case, the index 3 is missing. So when I return this through an API, it is returned as an object with keys, 0,1,2,4,5.

4
  • 1
    array_unique() does not convert your array into an object. Commented Mar 13, 2017 at 22:34
  • it doesn't convert it into an object, it turns it into an associated array Commented Mar 13, 2017 at 22:34
  • Okay, but I then return this item through an API interface, and Javascript receives it as an object. Commented Mar 13, 2017 at 22:36
  • 1
    Are you doing anything like json_encode() when you return the array? Commented Mar 13, 2017 at 22:37

2 Answers 2

2

The function array_unique() filters out equal values so the reason why #3 of the index is missing is because its equal to #0.

You can re-index the array with array_values():

var_dump(array_values(array_unique($errors, SORT_REGULAR)));

JavaScript perceives PHP's associative array's as an object because it only understands numeric keyed arrays.

You should be using to communicate between both languages:

echo json_encode($errors);

As this would cause in the outer the value to be turned into an array and turn each item into an object.

var arr = JSON.parse(outputofjson_encode);

console.log(arr[0].id);
Sign up to request clarification or add additional context in comments.

Comments

0

I ended up using array_values:

$errors = [];
for ($i = 0; $i < 3; $i++) {
    $errors[] = [
        'id' => $i
    ];
}

$errors[] = [
    'id' => 0
];

for ($i = 3; $i < 5; $i++) {
    $errors[] = [
        'id' => $i
    ];
}

$errors = array_values(array_unique($errors, SORT_REGULAR));

1 Comment

Cause I did not see your response! I marked yours as a the solution

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.