Returning true on every iteration of array_key_exists() in php

458 Views Asked by At

What am I trying to get is..

I do not know check_mobile_exists( $mobiles, $electronics ) this function is returning true all time. I want true when $mobile array key is existed in the $electronics key list and false when not existed. On this result basis I am looping the post result. But as I said that function is returning true on every iteration. Any one to suggest me what should I do now?

function check_mobile_exists(  $mobiles, $electronics ) {
    foreach( $mobiles as $mobile => $price ) {
        if( array_key_exists( $mobile, $electronics ) ) {
            return true;
        }
        return false;
    }
}

$mobiles = array(
    'iPhone' => '$350',
    'tablet' => '$100',
    'samsung' => '$200',
    'walton'  => '$60'
);

$electronics = array(
    'iPhone' => 'OK',
    'tablet' => 'will do',
    'walton' => 'No need'
);

while( have_posts() ): the_post();
    if( check_mobile_exists(  $mobiles, $electronics ) ){ // returning only true on every iterating
        echo get_the_title() .' do something....<br />';
    } else {
        echo 'Do another....';
    }
endwhile;
2

There are 2 best solutions below

6
On BEST ANSWER

Try this

$mobiles = array(
    'iPhone' => '$350',
    'tablet' => '$100',
    'samsung' => '$200',
    'walton'  => '$60'
);
$electronics = array(
    'iPhone' => 'OK',
    'tablet' => 'will do',
    'walton' => 'No need'
);

while( have_posts() ): the_post();
  foreach( $mobiles as $mobile => $price ) {
    if( array_key_exists( $mobile, $electronics ) ) {
        echo get_the_title() .' do something....<br />';
    }else{
        echo 'Do another....';
    }   
  }
endwhile;

UPDATED: So as you said, without using another function you can do this.

5
On

Do it witout check mobile function

$mobiles = array(
    'iPhone' => '$350',
    'tablet' => '$100',
    'samsung' => '$200',
    'walton'  => '$60'
);
$electronics = array(
    'iPhone' => 'OK',
    'tablet' => 'will do',
    'walton' => 'No need'
);




while( have_posts() ): the_post();
  foreach ( $mobiles as $m_key => $mobile ) {
    if ( array_key_exists( $m_mey, $electronics) ) { 
        do somethin
    } else { 
        do somethin
    }
}
endwhile;