1

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.

1

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.