NorS
NorS

Reputation: 158

Error: undefined index?

I get this array from a function (var_dump()):

...{ [0]=> string(7) "user_id" } [1]=> array(1) { [0]=> string(7) "user_id" } [2]...

When I try to separate the values with:

$var2 = $var['user_id']

I get the error "undefined index 'user_id'", even though, as you can see, the name of the value is "user_id", and I've checked my database a hundred times, and that IS the name of the index.

What other possible sources of error are there?

I appreciate any help! Thank you in advance!

function get_subscribitions($user)
{

$user = mysql_real_escape_string ($user);

  $sql = "SELECT * FROM `subscribe` WHERE subscriber = '$user'";

 $result = mysql_query($sql);

  $rows = array();

  while ($row = mysql_fetch_assoc($result)) {
      $rows[] = $row;
  }

  mysql_free_result($result);

  return $rows;

Can anyone pinpoint where in the above code, I make the mistake leading to this problem? Thanks.

Upvotes: 1

Views: 4017

Answers (6)

Punit
Punit

Reputation: 1120

error because the user_id is not an index it's a value having index 0

Upvotes: 0

ComFreek
ComFreek

Reputation: 29424

user_id is not an array key (that can be accessed by []), it is an value.

But you can use array_search()

$index = array_search('user_id', $your_array);

var_dump(  $your_array[$index]  );

Upvotes: 0

rlemon
rlemon

Reputation: 17666

the index is [0]. I don't think you have this structured correctly. The index is the left side of the declaration, the value is the right. You have assigned all values to "user_id" with incremental index.

Upvotes: 0

Till Helge
Till Helge

Reputation: 9311

You are mistaken. The structure of the array is like this:

array:
    [0] => array:
        [0] => "user_id"
    [1] => array:
        [0] => "user_id"

You need to access it like this: $var[0][0] and you will get user_id. Most likely you did something wrong when setting up the array.

Upvotes: 1

Andre
Andre

Reputation: 3181

The array key 0 contains a string called 'user_id' but there is no key named 'user_id', hence why you're getting the error.

I suggest you take a look at how you're compiling this data (query results perhaps?).

Upvotes: 1

ka_lin
ka_lin

Reputation: 9432

[0] is the index and the data is "user_id"

Upvotes: 1

Related Questions