falcon
falcon

Reputation: 357

PHP array_push() returns numeric keys too instead only string keys

I am trying to fetch data from MySQL. Because I am still learning PHP and MySQLi, I do not completely understand why this code prints double results with numeric keys too. I need push only string keys with values. Thanks for some direction.

code

if ( $r = $mysqli -> query ( $q ) ) {
    ${ 'err_css_' . $err_asid } = array ();
    while ( $row = mysqli_fetch_array ( $r ) ) {
        array_push ( ${ 'err_css_' . $err_asid }, ${ 'err_css_' . $err_asid }[$row['language_asid']]=$row['value'] );

    }
    print_r ( ${'err_css_' . $err_asid } );
}

result:

Array (
  [ces] => background:czech_flag_url;
  [0] => background:czech_flag_url; // i dont want numeric key
  [eng] => background:english_flag_url;
  [1] => background:english_flag_url; // i dont want numeric key
)

Upvotes: 0

Views: 447

Answers (3)

georg
georg

Reputation: 215009

The problem is that you're using array_push incorrectly. Actually, you don't need it at all:

if ( $r = $mysqli->query ( $q ) ) {
    $css = array ();
    while ( $row = mysqli_fetch_array ( $r ) ) {
        $css[$row['language_asid']] = $row['value'] );
    }
}

Also, I'd suggest that you don't use "variable variables". This is an essentially useless feature, that does nothing but reduce readability of your code. Use arrays or objects:

${ 'err_css_' . $err_asid } = array (); // NO

$err_css[$err_asid] = array ();         // yes

Upvotes: 2

Swapnil
Swapnil

Reputation: 301

Instead of using mysqli_fetch_array You need to use mysqli_fetch_assoc

Upvotes: 1

Edward
Edward

Reputation: 1883

The reason it is showing double results is because there is double results! mysqli_fetch_array() produces both associative and numerical arrays with identical values. Consider either using mysqli_fetch_assoc() or using is_numeric($key) to filter the results further.

Upvotes: 0

Related Questions