2

I use this code to check if values exist in an array:

if (!in_array(array("Product code","Price","Supplier","Cost Price"), $data)) {
        die("You are missing fields");
     }

Works fine but I would like it to return the value that does not exist so if th array was this:

$data = array("Price","Supplier","Cost Price");

PHP would return "Product code is not in array"

3 Answers 3

4

Use array_diff to find difference in multiple arrays comparison.

    $array1 = array("a" => "Product code","Price","Supplier","Cost Price");
if (!in_array($array1, $data)) {
        die("You are missing :" . print_r(array_diff($array1, $data)));
     }

From the PHP manual:

<?php
$array1 = array("a" => "green", "red", "blue", "red");
$array2 = array("b" => "green", "yellow", "red");
$result = array_diff($array1, $array2);

print_r($result);     /* This will print: BLUE */
?>

More information here: http://php.net/manual/en/function.array-diff.php

Sign up to request clarification or add additional context in comments.

Comments

0

Have a look at http://www.php.net/manual/en/function.array-diff.php and http://www.php.net/manual/en/function.array-intersect.php ; with these functions, you can check what's the difference (or common part) of two arrays and iterate through the differences (or common parts) to tell the user exactly what's missing/common.

Comments

0

you can use the array_diff_assoc -Computes the difference of arrays with additional index check

<?php
  $array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red");
  $array2 = array("a" => "green", "yellow", "red");
  $result = array_diff_assoc($array1, $array2);
   print_r($result);
?>

or use in_array like

$os = array("Mac", "NT", "Irix", "Linux");
if (in_array("Irix", $os)) {
    echo "Got Irix";
}

to check all array you can use something like

foreach($array as $val){
if (in_array($val, $os)) {
        echo "Got Irix";
    }

}else{
     //show error

}

1 Comment

array_diff is clearly the better way to do this, index checks are not needed here.

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.