Learn, Share, Build

53
October 12, 2017, at 5:20 PM

i want to compare two values in one php array but the code stops when i compare even when the conditions is true i want to know how can i compare the two values here is my code :

$i=0;$cmpt=0;
foreach($newarray as $newarray1){
    $j=0;
    while ($newarray1[$i]!==$newarray1[$j]){ // the iteration dont get in here even when the condition is true
        $j+1;
        var_dump($j);
    }
    if ($i=$j){
        $couleur[]=$Tcouleur[$cmpt];
        $cmpt+1;
    }else{
        $couleur[]=$Tcouleur[$j]; 
    }
    $i+1;
}
var_dump($couleur);
Answer 1

In your while loop, does $j+1 should not be $j++ or $j = $j + 1 ?

I know it's not the problem your asking...but same for your $i+1 at the end and your $cmpt

Now I think you want this :

$values = ['abc','def', 'hij','klm', 'def', 'klm','nop'];
$couleurs = ['rouge','vert','bleu','jaune','rose'];
$couleurPourValeur = [];
$increment = 0;
foreach($values as $value){
    if(!isset($couleurPourValeur[$value])){
        $couleurPourValeur[$value] = $couleurs[$increment];
        $increment++;
    }
}
print_r($couleurPourValeur);
Answer 2

This is probably because of the line

$j+1;

your both variables ($i and $j) are not being updated in the while loop, causing an infinite loop. ( checking the same values all the time, if the condition is true an infinite loop, else the code will never enter the loop and exit. )

change $j+1; with either $j++; or $j = $j + 1;

Moreover as @apomene shows,

if your array can have multiple types,

The !== operator checks both the type and the equality. If your array has same types ( for e.g int ) this would not create a problem tho. With the same types !== and != are the same thing practically. Else, it (!==) also checks for type equality. To elaborate,

$a = 1;
$b = '1';
$c = 2;
$d = 1;
$a == $b  //  TRUE   ( different type, equal after conversion - char <-> int)
$a === $b //  FALSE( different types - int vs char)
$a == $c  //  FALSE( same type not equal)
$a === $d //  TRUE ( same type and equal)

Further reading available in this question.

Lastly, you seem to have a confusion between assignment and comparison of a variable. ( $i = $j vs $i == $j )

Check the php manual for assignment vs comparison of variables.

READ ALSO
Learn, Share, Build

Learn, Share, Build

Is it possible in php not to display "Parse" error on a web page (more like hiding all error including parse error on a production environment)?

55
Learn, Share, Build

Learn, Share, Build

I can't understand this errorI tried all things but can't solve this

49
Learn, Share, Build

Learn, Share, Build

I am using queue function of laravel to send emailBut I think it is not working because it slow down the page process when sending large emails and do data is being saved in jobs table

52
Learn, Share, Build

Learn, Share, Build

I am trying to hit my login details to server directly instead of hitting DBPlease help me how to do this

27