0

i have an array and i generate a random number that might exist in the array and i am trying to see if the random number is in the array. If it exists in the array it will give a user a certain item, if its not in the array i want it to do nothing. I wrote it all out on a demo page to test it out and i keep getting an error back when the random # isn't in the array. Am I checking if the # is in the array correctly? I cannot for the life of me figure it out.

If you need more info please let me know.

Error:

Notice: Undefined offset: 10 in C:\xampp1\htdocs\hvp\battlemasters\play\text.php on line 17

Code:

$items_list = array();
$enemy_items = "1|7|8|10|11";

// Split Items
$enemy_item = explode("|",$enemy_items);
foreach($enemy_item as $item){
    array_push($items_list,$item);
}

// Get Total # Of Items In Array
$count = count($items_list);

// Start Random # Drawing
$start = 1;
$end = $count*2;
$random = rand($start,$end); 

// Check If $random Exists In Array
if (in_array($items_list[$random],$items_list) == TRUE) {
    // Item Exists So Lets Give The Item To The User

}

EDIT now for the $enemy_items = $r1['items'] i just added in the database 1 item for the enemy to test it out and the item # is 7

$q1 = 'SELECT * FROM `enemies` WHERE `id`="'.$enemy_id.'"';
$rq1 = mysql_query($q1);
$r1 = mysql_fetch_array($rq1);
$enemy_items = $r1['items'];

$items_list = array();

// Split Items
$items_list = explode("|",$enemy_items);

// Get Total # Of Items In Array
$count = count($items_list);

// Start Random # Drawing
$start = 1;
$end = $count*2;
$random = rand($start,$end); 

// Check If $random Exists In Array
if (in_array($random,$items_list)) {
    // Check if character already has the item in inventory
    $query = 'SELECT * FROM `characters` WHERE `user_id`="'.$_SESSION['user'].'" AND `iid`="'.$random.'" AND `cat`="items"';
    $r_query = mysql_query($query);
    $result = mysql_fetch_array($r_query);
    $exists = mysql_num_rows($r_query);
    if($exists == 1) {
        $quantity = $result['quantity'];
        // Update Characters Inventory
        $query = "UPDATE `characters_inventory` SET `quantity`='".$quantity++."' WHERE `user_id`='".$_SESSION['user']."' AND `iid`='".$random."' AND `cat`='items'";
        mysql_query($query);
    }else{
        // Insert New Item
        $query = "INSERT INTO `characters_inventory` (`user_id`,`iid`,`cat`,`quantity`) VALUES ('".$_SESSION['user']."','".$random."','items','1')";
        mysql_query($query);
    }

}

MySQL Stuff:

CREATE TABLE IF NOT EXISTS `enemies` (
`id` int(255) NOT NULL,
`name` varchar(255) NOT NULL,
`type` varchar(255) NOT NULL,
`icon` varchar(255) NOT NULL,
`items` varchar(255) NOT NULL
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=94 ;

INSERT INTO `enemies` (`id`, `name`, `type`, `icon`, `items`) VALUES (1, 'Dragon', 'Dragon', 'images/enemies/Dragon_1_1.png', '7');

3 Answers 3

2

It's simply:

if (in_array($random, $items_list))
Sign up to request clarification or add additional context in comments.

Comments

2

Modify last condition:

// Check If $random Exists In Array
if (isset($items_list[$random])) {
    // Item Exists So Lets Give The Item To The User

}

5 Comments

@rackemup420: have you actually checked that this does what you want?
ok so i tried this and it works perfectly! thank you so much!
@KarolyHorvath: We answered last, but it actually seems that we are the only ones who really got what he wanted to do, lol. i'm quite surprised that no one actually noticed that the OP isn't asking that... Nevermind.
HaHa, was I sleeping???? This might actually cause a bug. I've edited the answer.
Still doens't solve the problem, you're still checking if the INDEX exists (the key) and NOT the value.
2
$items_list = array();
$enemy_items = "1|7|8|10|11";

// Split Items
$items_list = explode("|",$enemy_items);

// Get Total # Of Items In Array
$count = count($items_list);

// Start Random # Drawing
$start = 1;
$end = $count*2;
$random = rand($start,$end); 

// Check If $random Exists In Array
if (in_array($random,$items_list)) {
    // Item Exists So Lets Give The Item To The User
  echo "it exists.";
}

If you want to check if $random exists in the $items_list array, just check if $random exists, don't check if the index of random exists.

Also, the foreach is not needed here, explode already returns an array, therefore your string "1|7|8|10|11" will automatically be converted into an array.

EDIT:

To clearify:

by checking if $items_list[$random] exists, you're actually asking to the array:

"Does the key $random exist in the array?", which MAY eventually be true, since the array is [1,7,8,10,11], but actually truly is just this:

array(
0 => 1,
1 => 7,
2 => 8,
3 => 10,
4 => 11
);

THEREFORE, if $random is for some reasons 3, the if will evaluate to TRUE despite there truly is no value in the array which is 3, but there is a key which is 3.

be careful.

Edit 2:

Fixing the == TRUE which is not needed.

Edit 3:

GOING DEEPER ::

Since you look confused, I will give you a brief example of what happens.

Scenario 1:

in_array($items_list[$random], $items_list)

Supposing that the array is the one above:

array(
0 => 1,
1 => 7,
2 => 8,
3 => 10,
4 => 11
);

There are two cases:

A: $random is either 0 [impossible],1,2,3,4.

B: $random is any other number.

Case A:

if $random is 2, the if will go on like this:

First, it will check if the KEY 2 is set, therefore, your if can be interpreted as this:

if (in_array($items_list[2], $items_list))

However, since the key 2 exists, it really correspond to this:

in_array(8, $items_list)

Because the KEY 2 of the $items_list array exists and has a value of 8 (check the above array).

At this point, the if is like: "Well, is there any VALUE which is 8 into the $items_list array?" The answer is TRUE, therefore the if will evaluate DESPITE THERE ISN'T REALLY ANY VALUE WHICH IS 2 INTO THE ARRAY.

Case B:

Let's suppose that $random is 10 (which is currently the maximum value anyway).

PHP will try to find what is the value of the corresponding key like before, however, the array can be also seen in this way:

array(
0 => 1,
1 => 7,
2 => 8,
3 => 10,
4 => 11,
5 => null,
[...]
10 => null
);

So, since the key 10 ha NO VALUE, php will throw you a NOTICE, by telling you "hey sir, the key 10 has no value, because it is not set.", also known as: undefined offset: 10

Scenario 2:

in_array($random, $items_list)

In this case $random can have any value in this universe that the in_array will always return either true or false, because it will just check if the VALUE exists in the array. (you can find a further explanation of this point at the very beginning of the post).

Hope this helped.

8 Comments

Thank you for breaking it down and explaining, i see now what you are saying this is the most precise answer i was looking for thank you!
@rackemup420: you should rather accept karoly Horvarth answer, he is the first one who wrote the correct answer, I wrote it after him, the fact is that all the other answers shouldn't exist there ;) Edit::I've added a clearer explanation in order to explain why Karoly Horvarth's answer is the correct one. Please take a look at it if you're still confused about why you're checking the value and not the index.
== TRUE is an anti-pattern. the if already does that check, it's not needed.
so $random gives me the actual entry in the array and not the key right? sorry brain farting moment lol
$random is a number generated between 1 and 10. by using in_array($random,$array) you check if the VALUE is in the array, by using in_array($array[$random],$array) you check if the VALUE with the $random KEY exists into the array. You don't want that, believe me. Also, as Karoly Horvath said above, you can also remove the == true, because the if (true) already evaluates. In any case yes, if the if evaluates, that means that $random exists into the array and that, therefore, it is actually an entry which exists into the array.
|

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.