Search code examples
phparray-push

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
)

Solution

  • 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