ThomasReggi
ThomasReggi

Reputation: 59455

Search arrays then echo with conditionals?

I'm trying to do somthing like this:

  $random = array("apple","celery","banana");

  $define_fruits = array("apple","banana","pears","mango");
  $define_vegetables = array("celery","lettuce","carrots","cucumber");

  if($random contains only fruits){
    echo fruits;
  }elseif($random contains only vegetables){
    echo vegetables;
  }elseif($random contains both fruits and vegetables){
    echo both;
  }

SOLVED:

$in_fruits = sizeof(array_intersect($random,$define_fruits));
$in_vegetables = sizeof(array_intersect($random,$define_vegetables));

      if($in_fruits >= 1 && $in_vegetables >= 1){
          echo "in_fruits and in_vegetables "; 
        }elseif($in_fruits === 0 && $in_vegetables >= 1){
          echo "in_fruits "; 
        }elseif($in_fruits >= 1 && $in_vegetables === 0){
          echo "in_fruits"; 
        }

Progression:

$in_fruits = count(array_intersect($random,$define_fruits));
$in_vegetables = count(array_intersect($random,$define_vegetables));

if( $in_fruits ){
  if( $in_vegetables )
    echo "both";
  else
    echo "fruits";
}elseif( $in_vegetables ){
  echo "veggies";
}else{
  echo "neither ";

Upvotes: 1

Views: 79

Answers (3)

daalbert
daalbert

Reputation: 1475

This could probably done more efficiently, but this is a simple way:

$random = array("apple","celery","banana");

$define_fruits = array("apple","banana","pears","mango");
$define_vegetables = array("celery","lettuce","carrots","cucumber");

if( count(array_intersect($define_fruits,$random)) ){
  if( count(array_intersect($define_vegetables,$random)) )
    echo "both";
  else
    echo "fruit";
} elseif( count(array_intersect($define_vegetables,$random)) ){
  echo "vegetables";
} else {
  echo "neither";
}

Upvotes: 2

soulkphp
soulkphp

Reputation: 3833

The simplest solution would be:

if ( in_array($define_fruits, $random) && ! in_array($define_vegetables, $random) ) {
   // Only fruits
}elseif ( ! in_array($define_fruits, $random) && in_array($define_vegetables, $random) ) {
   // Only Vegetables
}elseif ( in_array($define_fruits, $random) && in_array($define_vegetables, $random) ) {
   // Both fruits and vegetables
}

Upvotes: -1

ADW
ADW

Reputation: 4080

You probably want to look at array_intersect:

http://php.net/manual/en/function.array-intersect.php

Upvotes: 6

Related Questions