php strings

C++, C#, Java, PHP, ect...
Post Reply
alexander19
Posts: 180
Joined: Fri Apr 02, 2010 1:05 pm

php strings

Post by alexander19 »

Hello everyone!

Been working on an inventory system which stores all items in a string:
E.g:

Code: Select all

$inventory = "Sword,Potion,Sword,Dagger";
The thing is that I can manipulate the string by using explode and foreach for adding extra items to it but the problem comes when I want to delete an item, especially one that appears multiple times(like the Sword in the above example).
I tried str_replace,but it replaced all items of the same kind :

Code: Select all

$item = "Sword";
$string = str_replace("$item", "", $inventory);
My question is,how can I replace only one instance of a string that appears multiple times?
User avatar
Chris
Posts: 1581
Joined: Wed Sep 30, 2009 7:22 pm

Re: php strings

Post by Chris »

If you looked at the str_replace documentation you'd find out:
mixed str_replace ( mixed $search , mixed $replace , mixed $subject [, int &$count ] )

Code: Select all

$string = str_replace("$item", "", $inventory, 1);
 
Fighting for peace is declaring war on war. If you want peace be peaceful.
alexander19
Posts: 180
Joined: Fri Apr 02, 2010 1:05 pm

Re: php strings

Post by alexander19 »

damn didnt checked that...thx a lot :D
Baseball435
Posts: 548
Joined: Sun May 30, 2010 3:49 am

Re: php strings

Post by Baseball435 »

what i did for my inventory is that when someone bought something from the shop it would insert into the table 'inventory' and it the values in the table would be owner, name, strbuff, defbuff, sneakbuff, agilitybuff, consumable, equipable, equiped and then when they bought it i would insert there name as the owner and then have the name as the item name and then i would fill in the rest. Then for the inventory part i just had a query that said SELECT * FROM inventory WHERE owner = '$username' and then i had it as a while loop so that it would post every thing that they had in their inventory. It works really good too
alexander19
Posts: 180
Joined: Fri Apr 02, 2010 1:05 pm

Re: php strings

Post by alexander19 »

Well I have a drag & drop inventory made in jquery UI,and the inventory database table is actualy made from 2 parts...the tabs with the items you currently have equipped , which stores 1 item each and the normal inventory which stores 18 items,so rather than creating a new table with 18 tabs I've created only a tab that holds a string with all the items.

Here is a screen:
Image
Post Reply

Return to “Coding”