0

If I create a manual array in PHP:

$numbers = array(3,5,7,8,10,12);

Then, inside a loop where $j is incrementing, I can use:

if (in_array($j, $numbers)) { //THIS } else { //THAT }

for some logic to do 'this or that' on the third, fifth, seventh, eighth, tenth and twelfth iteration of a loop.

I'd like the content of $numbers to come from a MySQL query result.

However, if I grab an array using the below code, the array is not built the same and I cannot reference it from in_array ($conn is obviously the connection details not provided here):

$numbers_from_query_sql= "SELECT (round*1) as round FROM event";
$numbers_from_query = mysqli_query($conn, $numbers_from_query_sql);

$numbers_ms_array= array();
while ($row = mysqli_fetch_assoc($numbers_from_query)) {
    $numbers_ms_array[] = $row;
}

The var_dump($numbers_ms_array) of the above produces:

array(6) { [0]=> array(1) { ["round"]=> string(1) "3" } [1]=> array(1) { ["round"]=> string(1) "5" } [2]=> array(1) { ["round"]=> string(1) "7" } [3]=> array(1) { ["round"]=> string(1) "8" } [4]=> array(1) { ["round"]=> string(2) "10" } [5]=> array(1) { ["round"]=> string(2) "12" } }

If I then pass $numbers_ms_array to the in_array code, it does not work .

Note that in the database, the 'round' column is varchar(3).

How can I get a simple array (like my first manual example) from the result of my MySQL query (with all of the results as integers, if that's also necessary)?

2
  • $numbers = array_map($numbers_ms_array, function($element) { return (int)$element['round']; }); Commented Jan 24, 2022 at 16:23
  • 1
    $numbers = array_column($numbers_ms_array, 'round'); Commented Jan 24, 2022 at 16:24

1 Answer 1

1

You are assigning the whole $row to your numbers array which is giving you the entire row as an array in your values.

It sounds like you want only the value so you should assign just the column you want instead:

$numbers_ms_array[] = $row['round'];
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, a simple addition, I was close... I am an amateur programmer so hoped it would be something silly I'd missed.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.