1

I have an array that displays it's keys and values twice. Here is an example of the way it displays data:

Array ( 
[0] => 38 
[1] => 38 
[2] => 10 
[3] => 10 
[4] => B 
[5] => B 
[6] => 5 
[7] => 5 
[8] => 5 
[9] => 5 
[10] => 5 
[11] => 5 
[12] => 5 
[13] => 5 
[14] => 5 
[15] => 5 
[16] => 5 
[17] => 5 
[18] => 5 
[19] => 5
) 

I tried looking for a solution on SO but I only found cases with for each. Tried selecting only even keys but haven't managed to do that. array_unique() wouldn't work in my case since there is a chance that I have equal values for different fields.

What could be the problem that causes it to display twice?

<?php
include_once "connect.php";

$intrebare_02 = mysqli_real_escape_string($con, $_POST['intrebare_02']);

    $i = 0;
    $array_sum=[];
     while ($i < 10){
      $i++;
       $sql =  "SELECT * FROM parteneri WHERE nr_intrebare = '$i' AND varianta_raspuns = '$intrebare_02'";
       $result = mysqli_query($con, $sql);

       $final_array = array();
 if ($i % 2 == 0)
      while ($row = mysqli_fetch_array($result))
      {

        $final_array = array_values($row);
            $array_sum = array_map(function () {
                return array_sum(func_get_args());
            }, $array_sum, $final_array);
      }
}
print_r($final_array); 

Let me know if you need further clarification.

3
  • Do you mean you want to change [1,3,5] to [1,1,3,3,5,5]? Commented Feb 13, 2017 at 11:25
  • 1
    $row = mysqli_fetch_array($result, MYSQLI_NUM).... and then you don't need to do that array_values() call either Commented Feb 13, 2017 at 11:25
  • 1
    @MarkBaker Worked like a charm. Please post it as an answer so that I can accept it. If you could clarify the solution it would be great. Thank you! :) Commented Feb 13, 2017 at 11:27

1 Answer 1

2

By default, mysqli_fetch_array() returns an array with both associative (by column name) and enumerated keys (by order of columns) for each column of the row. You can specify whether you want just an associative array or just an enumerated array by using the MYSQLI_ASSOC or MYSQLI_NUM flags respectively as a second argument to the function.

Alternatively, you can use the mysqli_fetch_assoc() function to return just an associative array, or mysqli_fetch_row() to return just an enumerated array, or mysqli_fetch_object() if you want to get adventurous and return an object where there is a public object property for each column

Sign up to request clarification or add additional context in comments.

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.