0

I have created this

while ($data = mysqli_fetch_array($course_result, MYSQLI_ASSOC)) {
    print_r($data['course']);   
}  

Which prints this:

Array ( 
     [user_id] => 57 
     [course] => 6 
)
Array ( 
     [user_id] => 57 
     [course] => 5 
)

How can I create two variables that are equal to the values of the 'course' fields. So ideally, variable x ends up equalling to 6 and variable y equals 5 (essentially what I'm asking is how to extract the value from the mysql arrays and putting it into a variable)?

4
  • Will they always be 6/5, or will it always be 1st result as x and 2nd result as y, and will there always just be 2 rows returned? Commented Jul 19, 2014 at 15:59
  • @Sean no, the value of the course field won't always be 6/5. So yes, the 1st result = x, the second equal to y. Commented Jul 19, 2014 at 16:00
  • So there will never be more than two results from the query? What's the likelihood of needing a 3rd, 4th and so on variable? Commented Jul 19, 2014 at 16:02
  • while ($data = mysqli_fetch_array($course_result, MYSQLI_ASSOC)) { if(!isset($x)){$x=$data['course']['course'];}else{$y=$data['course']['course'];} }. This assumes only 2 rows returned from your query, and that it is only called once, as once $x is set, it won't be reset, and $y would continue to be reset. Commented Jul 19, 2014 at 16:07

3 Answers 3

2

There is no something as you called "mysql_arrays". They are normal arrays.

You can do for example:

$array = array();
while ($data = mysqli_fetch_array($course_result, MYSQLI_ASSOC)) {
   $array[] = $data; // probably this way and not $array[] = $data['course'];
}  

$x = $array[0]['course'];
$y = $array[1]['course'];
Sign up to request clarification or add additional context in comments.

1 Comment

also there is array_column function which can help you with the above ans..check the link ..w3schools.com/php/func_array_column.asp
0

I would suggest you using an array instead of a variable to store the values.

$arr= array();
while ($data = mysqli_fetch_array($course_result, MYSQLI_ASSOC)) {
    $arr[] = $data['course'];
}

1 Comment

note it should be $arr[] = $data['course']['course'] as according to the OP's code -> print_r($data['course']); returns Array ( [user_id] => 57 [course] => 6 )
0

Speculating a bit as don't have the full picture but I guess you're after something like this.

Get an array of the courses from your data

$data = array_map(function($value) {
    return $value['course'];
}, $data);

If there are only ever two results, assign each one to a variable :

list($x, $y) = $data;

If there are more than two results, you have an array of courses in $data from your query results.

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.