1

How can I extract only the indexes of the array_diff function?

$array1 = array("a" => "green", "red", "blue", "red", "pink");
$array2 = array("b" => "green", "yellow", "red");
$result = array_diff($array1, $array2);
print_r($result);

Instead of it showing: Array ( [1] => blue [3] => pink ) I want it to display only the indexes like this: 1, 3 (maybe inside a new array called $indexesresult) (Reason being that I am comparing an online (mysqli) array with a localhost (mysqli) array and I have to remove whitepaces before I can compare the arrays- I tried hundreds of ways around this but to no avail: array_diff does not like any type of whitespaces). With the indexesresult I can then get the original values back into the arrays to display the differences in a neat tabular format.

2 Answers 2

1

The array_keys would help.

$array1 = array("a" => "green", "red", "blue", "red", "pink");
$array2 = array("b" => "green", "yellow", "red");
$result = array_diff($array1, $array2);
$indexesresult=array_keys($result); //<----- Here
print_r($indexesresult);

OUTPUT :

Array
(
    [0] => 1
    [1] => 3
)
Sign up to request clarification or add additional context in comments.

1 Comment

Part2 for display: foreach($indexesresult as $item) { echo $item."<br>"; } echo "<br><br>"; foreach($indexesresult as $key => $item) { echo "Key ".$key.': '.$array1[$item]." from index: $item <br>"; }
1

Just try with:

print_r( array_keys($result) );

Comments

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.