dask
dask

Reputation: 19

How can I loop this array

php code:

<?php
$arVal = array('4','2','3','1','6','9','7');
$arLength = count($arVal);

for ($i = 0; $i < $arLength; $i++) {
    $val = '';
    $cVal = '';
    $ar = '';
    // $arNext shift $arVal(array)
    $arNext = next($arVal);
    // $val just contain string $tVal0, $tVal1...
    echo $val = '$tVal'.$i.'=';
    // $ar for loop value inside array 4,2,3,1...
    echo $ar = $arVal[$i].' [';
    // $cVal contain value math = 4+2*(1-4)
    echo $cVal = $ar+$arNext*(1-$ar).'] <br>';
}

i want to loop like this...

$tVal0 = $val0+$val1*(1-$val0);
$tVal1 = $val2+$val0*(1-$val2);
$tVal2 = $val3+$val1*(1-$val3);
$tVal3 = $val4+$val2*(1-$val4);
$tVal4 = $val5+$val3*(1-$val5); 

how to do looping like that (is it possible or not, if not i'm not using loop), look duplicate post then direct me. Thanks.

Upvotes: 0

Views: 100

Answers (1)

Jay S.
Jay S.

Reputation: 1327

If I understand the question correctly then try this. It may not be what you're asking, as I don't understand where $val? and $tVal? is coming from. Are you declaring it, or getting it from the array? And you seem to be assigning a variable after the echo keyword, is that meant to be in quotes?

echo "$tVal0 = $val0+$val1*(1-$val0)";
  //This one has to be done outside the loop b/c it's different

for($i=1,$i < 5,i++){
  $tVal_Name = 'tVal' . $i;
  $outside_val_name = 'tVal' . $i+1;
  $inside_val_name = 'tVal' . $i-1;
  echo "{$$tVal_Name}={$$outside_val_name}+{$$inside_val_name}*(1-{$$outside_val_name})";
}

To know more about variable variables, see the php documentation

Upvotes: 1

Related Questions