0

I've got the following sql query:

$sql = "SELECT lat, lang
        FROM users";

I then use the following code to put the results of the array into two arrays, one for lat and one for lang.

$i = 0;

foreach($results as $row) {
    $latArray = array();
    $langArray = array();
    $latArray[$i] = $row['lat'];
    $langArray[$i] = $row['lang'];          
    $i = ($i + 1);
}

However, it seems that only the last value that is passed to the array is stored. When I echo out each value of the array I get the following error: Undefined offset: 0 which I believe means theres nothing at latArray[0].

I'm sure I've missed something obvious here but why aren't all the values copied to the new array?

2
  • Move the "$latArray = array();" and line after that before foreach. Commented Apr 7, 2013 at 18:05
  • php.net/mysql_fetch_array Commented Apr 7, 2013 at 18:05

4 Answers 4

3
$i = 0;
$latArray = array(); //Declare once, do not redeclare in the loop
$langArray = array();
foreach($results as $row) {
    $latArray[$i] = $row['lat'];
    $langArray[$i] = $row['lang'];          
    $i = ($i + 1);
}
Sign up to request clarification or add additional context in comments.

Comments

1

Declare your array before the loop

$latArray = array();
$langArray = array();

foreach($results as $row) {
    $latArray[$i] = $row['lat'];
    $langArray[$i] = $row['lang'];          
    $i = ($i + 1);
}

Comments

1

You should put

$latArray = array();
$langArray = array();

Before foreach cycle (like you do with your counter $i), 'cause with every new value from $result it resets thous values..

so your code will look like:

$i = 0;
$latArray = array();
$langArray = array();
foreach($results as $row) {
    $latArray[$i] = $row['lat'];
    $langArray[$i] = $row['lang'];          
    $i = ($i + 1);
}

Comments

0

use fetch_assoc instead:

$latArray = array();
        $langArray = array();
    while($row = mysql_fetch_assoc($your_query)){



    $latArray[$i] = $row['lat'];
    $langArray[$i] = $row['lang'];          
    $i++;
}

if u are using msqli us mysqli_fetch_assoc

1 Comment

:) true the array was declared inside the loop

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.