Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

array_diff & renumbering numeric keys

(I'm a beginner)

My script uses the standard

$c = 0;
$t = count($array);

while ($c < $t) {
  $blah = $array[$c];
  ++$c;
}

rather extensively. But I just ran into a situation where I also need array_diff and it breaks that all to hell because now the numeric keys have gaps. I'm getting Undefined offset errors all over the place.

How do I reset the numeric keys of an array? The order of the objects in the array is irrelevant.

like image 691
Drew Avatar asked Mar 04 '10 12:03

Drew


People also ask

How can I compare one array to another in PHP?

The array_diff() function compares the values of two (or more) arrays, and returns the differences. This function compares the values of two (or more) arrays, and return an array that contains the entries from array1 that are not present in array2 or array3, etc.

What is difference between array and [] in PHP?

Note: Only the difference in using [] or array() is with the version of PHP you are using. In PHP 5.4 you can also use the short array syntax, which replaces array() with [].

How do I check if two elements are in the same array?

The Arrays. equals() method checks the equality of the two arrays in terms of size, data, and order of elements. This method will accept the two arrays which need to be compared, and it returns the boolean result true if both the arrays are equal and false if the arrays are not equal.

How can I get unique values from two arrays in PHP?

The array_diff() (manual) function can be used to find the difference between two arrays: $array1 = array(10, 20, 40, 80); $array2 = array(10, 20, 100, 200); $diff = array_diff($array1, $array2); // $diff = array(40, 80, 100, 200);


1 Answers

To reset the keys, you can use array_values():

$array = array_values($array);
like image 85
Tatu Ulmanen Avatar answered Sep 27 '22 20:09

Tatu Ulmanen