user1823406
user1823406

Reputation:

Checking array against another array

Say I have the following two arrays:

$array = Array("Julie","Clive","Audrey","Tom","Jim","Ben","Dave","Paul");
$mandt = Array(1,0,0,1,0,0,1,1);

The numbers signify whether the names are valid or not. 1 is valid 0 is not. I need to check through the names and echo their name and then "true" if the name is valid and "false" if it is not, i.e:

Julie: True
Clive: False
Audry: False

Etc...

Could anybody help me out please?

THanks.

Upvotes: 2

Views: 126

Answers (5)

user1726343
user1726343

Reputation:

for($i=0, $count=count($array); $i<$count; $i++){
    echo $array[$i] . ": " . ($mandt[$i]? "True":"False") . "<br/>";
}

Upvotes: 2

Pedro Cordeiro
Pedro Cordeiro

Reputation: 2125

Instead of looping and comparing the arrays, you could make a Hashtable-like array, like this:

$arr = array(
    "Julie" => true,
    "Clive" => false,
    "Audrey" => false,
     "Tom" => true
     [...]
);

This way, you can just run something like that:

if ($arr["Julie"]) {
    //Julie is a valid name!
} else {
    //Julie is not a valid name!
}

This would be way more efficient than looping through the array.

Upvotes: 1

deceze
deceze

Reputation: 522155

$values = array_combine($array, $mandt);
$values = array_map(function ($i) { return $i ? 'True' : 'False'; }, $values);

var_dump($values);

// or loop through them, or whatever

Upvotes: 2

Carsten
Carsten

Reputation: 18446

Why don't you just loop through the arrays?

$array = Array("Julie","Clive","Audrey","Tom","Jim","Ben","Dave","Paul");
$mandt = Array(1,0,0,1,0,0,1,1);

$c = count($array);
for ($i = 0; i < $c; i++) {
  echo $array[$i] . ": " . (($mandt[$i] == 1)?"True":"False") . "\n";
}

Upvotes: 1

George
George

Reputation: 36784

So something like this foreach() loop?...

foreach($array as $key => $value){
    echo $value.": ";
    echo $mandt[$key] ? "True" : "False";
    echo "<br />";
}

Upvotes: 3

Related Questions