2

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.

5 Answers 5

3

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

foreach($array as $key => $value){
    echo $value.": ";
    echo $mandt[$key] ? "True" : "False";
    echo "<br />";
}
Sign up to request clarification or add additional context in comments.

Comments

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

var_dump($values);

// or loop through them, or whatever

Comments

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

1 Comment

for little optimization, you can store $cnt = count($array); then use in for loop
1

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";
}

Comments

1

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.

Comments

Your Answer

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