How to access looped array values outside the loop?

I am a newbie in php, and I have a proble with associative arrays when looped.

The array is anassociative array of the form: $myarray = array(‘id’=>id, ‘name’=>name, ‘num1’=> 6.5, ‘num2’=> 0.385);

It is being passed from a table into arrays dynamically.

<input type='text' name="myArray[<?php echo $row['id']; ?>]" value=''>

$myarray = $_POST['myArray']; // i.e  $myarray = $_POST['name'];

Then I loop through to get only the selected table rows from the index page

function addValues($x,$y,$z){return $x+$y+$z;}

foreach($myarray as $key=>$value)
{
    $result = mysql_query(SELECT * FROM `test_tbl` WHERE id IN($key)");
    if(!empty($value))
    {
    while ($row = mysql_fetch_array($result))
    {
// array number 1
    $val[] = array('id'=>$row['id'],
        'name'=>$row['name'],
        'Number1'=>$row['num1'],
        'Number2'=>$row['num2']);

}//end of loop
    
    }//end of condition

//************** this is my problem ************

I will like to add $value (from user input in text box) unto $row['num1'] and $row['num2']  
addValues($value, $row['num1'], $row['num2'])// this does not react
}

To simplify my question, is it possible to access processed data from a loop(like $row[‘num1’] and $row[‘num2’] from the while loop) and use it in a function (such as addValues) or another loop?

I will welcome any suggestions thanks in advance.
NB: I know mysql_ is deprecated, I am using PDO, but I want to understand the logic before going PDO.

I don’t see where not using PDO and using msyql would help you in your problem? If anything it will compound the problem(s) in my opinion. Now with your problem, sorry but your explanation of what your problem is totally confused me. However, If I were to guess I would say that you should be tackling this from MySQL and not PHP, by that I mean add the rows or columns (or both) up using mysql then simply add the value the user inputs. However, there is probably someone out there that can better answer this thread.

The part where your adding to the $val array could be more simplified to:

$val[‘value_here’] = $row[‘database_column_name’];

Foreach entry or in the loop create a copy of the array. Then in the form but for the inputs value attribute $val[‘value_here’];

Try

.....
}//end of loop
var_dump($row);
var_dump($val);
    }//end of condition
.....

see anything helpful?

It seems a little confused to me, but here are some suggestions:

  • You can creating more one line in your multiassoc $val and put, something like ‘value’ => $value.
  • Use $key as array $val index
  • Pass array $val to your function, something like addValues($val);

I hope this options can help you and If you explain a little more, we can help you better :smiley:

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.