Dan
Dan

Reputation: 1244

If is in array?

Really struggling with this one:

I have an existing foreach, containing an if loop looking for specific values. But I also have an array containing values which if found should have the same action taken as the specific values:

Here I loop through and when values are between 5 and 9, I take the value of $datacolvalue and add it to another array as an integer rounded to 2 decimal places.

Otherwise, add it as a string, untouched.

$data_row = array();
$count = 1;
foreach ($row->COLUMN as $datacolvalue){

    if($count > 4 && $count < 10)
        $data_row[] = round((float)$datacolvalue, 2);
    else
        $data_row[] = (string)$datacolvalue;

      $count++;
}

What I want to do, is is do the same thing $data_row[] = round((float)$datacolvalue, 2); if the value of $count is in a static array named $array_to_round which looks like this (values are different each time the php is run:

array(12,34,56,78);

I though about adding a foreach inside the "else" condition but I cannot get my head around it. Is a for/while/loop the answer?

In a nutshell, for each $datacolvalue, if $count is (> 4) and (< 10) OR is present in the $array_to_round array place in array as int and round, otherwise, place it as a string.

Upvotes: 1

Views: 538

Answers (1)

Brad Christie
Brad Christie

Reputation: 101594

Use in_array to check if the value exists in the other array, then add it as necessary,

I would also store the rounded value if you plan to use it as a check and a setter.

Upvotes: 4

Related Questions