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');