skip to Main Content

I have the following array:

$moods = array("neutral", "happy", "sad");
$newarray= "";

I want to use an if-loop that goes through the array $mood in sequence and gives a different output based on what $moods value is selected

for ($x = 1; $x <= 7; $x++) {

[insert code for sequencing through $moods here]

if ($moods == "neutral") {
    $output1 = "1";
    $newarray.= $output1
}
else {
    $output2 = "0";
    $newarray.= $output2
}

with the desired output being that $newarray is filled with $output1 and $output2 values such that

$newarray= "1001001";

I have tried using array_rand:

for ($x = 1; $x <= 7; $x++) {

    $mood= array_rand($moods,1);

    if ($mood == "neutral") {
        $output1 = "1";
        $newarray .= $output1
    }
    else {
        $output2 = "0";
        $newarray.= $output2
    }

but the problem with this is that it selects a random variable from the $moods array, instead of going through it in sequence.

2

Answers


  1. Try this.

    $moods = ['neutral', 'happy', 'sad'];
    $newarray= '';
    
    foreach($moods as $mood) {
       $newarray .= $mood == 'neutral' ? '1' : '0';
    }
    

    Update based on updated question

    $moods = ['neutral', 'happy', 'sad'];
    $newarray= '';
    
    // initail index should be 0 to access correct value in $moods
    for($i = 0; $i <= 5; $i++) {
       $newarray .= $moods[$i % (count($moods))] == 'neutral' ? '1' : '0';
    }
    
    Login or Signup to reply.
  2. You could refer to an element of the array using the subscript ([]) operator:

    for ($x = 1; $x <= 3; $x++) {
        $mood = $moods[i];
        if ($mood == "neutral") { # Note that this should relate to $mood, not $moods
            $output1 = "1";
            $newarray.= $output1;
        } else {
            $output2 = "0";
            $newarray.= $output2;
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search