Notice: Uninitialized string offset: 1

Discussion in 'PHP' started by dineshsingh1984, Sep 9, 2014.

  1. #1
    my function is :
    function sele_orde($tb, $id, $ord)
    {
    $row[] = '';
    $sql = mysql_query("select * from $tb order by $id $ord");
    while($re = mysql_fetch_array($sql))
    {
    $row[] = $re;
    }
    return $row;
    }


    and call here :

    foreach(sele_orde('user_tb', 'id', 'desc') as $val)
    {

    echo $val[1]."::::".$val[2]."::::".$val[3];
    echo "<br>";
    }
    but here show the error and after showing result:

    Notice: Uninitialized string offset: 1 in D:\xampp\htdocs\ls\developer.php on line 103

    Notice: Uninitialized string offset: 2 in D:\xampp\htdocs\ls\developer.php on line 103

    Notice: Uninitialized string offset: 3 in D:\xampp\htdocs\ls\developer.php on line 103

    1::::firstname::::lastname


    Plz help me...........
     
    dineshsingh1984, Sep 9, 2014 IP
  2. donjajo

    donjajo Active Member

    Messages:
    14
    Likes Received:
    0
    Best Answers:
    1
    Trophy Points:
    51
    #2
    first print this, lets see what you have there

    print_r ( sele_orde('user_tb', 'id', 'desc') )
     
    donjajo, Sep 9, 2014 IP
  3. pmf123

    pmf123 Notable Member

    Messages:
    1,449
    Likes Received:
    81
    Best Answers:
    0
    Trophy Points:
    215
    #3
    is what you wrote the same as doing this?

    $row[0]=$re[0];
    $row[1]=$re[1];
    $row[2]=$re[2];

    and if there were more than 1 match, it would only return the last result?
     
    pmf123, Sep 17, 2014 IP
  4. brealmz

    brealmz Well-Known Member

    Messages:
    335
    Likes Received:
    24
    Best Answers:
    3
    Trophy Points:
    138
    #4
    $row[] = '';
    your first row has an empty string and your array will looks like this
    array('',array(0=>1,2=>'firstname',3=>'lastname'))


    replace it with $row = array(); instead of $row[] = '';
     
    brealmz, Sep 21, 2014 IP
  5. YoGem

    YoGem Active Member

    Messages:
    676
    Likes Received:
    8
    Best Answers:
    2
    Trophy Points:
    90
    #5
    Gee... no one noticed the error... ok, here is the solution.

    First understand the message:
    Assuming that $string = "Hello";
    echo $string[0] will return "H".

    Now, your code works but there's just an issue: you are declaring the array in a wrong way. When you want to declare an array you cannot do this:
    
    $array[] = "";
    
    Code (markup):
    Because what you are doing is to assign to the $array a subsequential value of "empty", hence you get the error that at offset 1 there are no chars to show.
    Instead, what you have to do is to declare the empty array like this
    
    $array = array();
    
    Code (markup):
    Why? Because like this the foreach will have just the exact numbers of rows to show instead of a empty row at the beginning and then the others.
     
    YoGem, Sep 22, 2014 IP