October 10, 200917 yr I have a php script with an integer variable that can equal 1 - 20. I want the variable to then change to a text string, depending on the number it was. I'm sure it has something to do with arrays, but have no real clue about them yet. Does anybody have any ideas? e.g 1 is cat, 2 is dog, 3 is snail. so if the variable was 1, it would be change to equal 'cat'. Thanks in advance.
October 10, 200917 yr I have a php script with an integer variable that can equal 1 - 20. I want the variable to then change to a text string, depending on the number it was. I'm sure it has something to do with arrays, but have no real clue about them yet. Does anybody have any ideas? e.g 1 is cat, 2 is dog, 3 is snail. so if the variable was 1, it would be change to equal 'cat'. Thanks in advance. My link Have a read through that and that will/should answer your question Ben
October 10, 200917 yr You could try a switch: switch($integer) { case 1: $animal="cat"; break; case 2: $animal="dog" break; //and so on default: $animal="tapir"; }
October 11, 200917 yr Author Thanks guys, I've got it now. I'm a bit of a newbie to php so thanks for your help!
October 11, 200917 yr A switch is a bad method to use. Just use an associative array $array = ( 0 => 'cat', 1 => 'dog', 2 => 'owl', 3 => 'pig', 4 => 'cow' ); echo $array[3]; // echos pig
October 11, 200917 yr Author Yeah I went for an array in the end, it seems to be working so far! I went for something a bit like this: $string = 1; //some integer $array=array(1=>"Cat",2=>"Dog",3=>"Rabbit",4=>"Mouse"); $string = $array[$string]; //changed to text string It's alright practice to put a variable in the [] right? lh
October 11, 200917 yr It's alright practice to put a variable in the [] right? Certainly is - otherwise iterating over the contents of an array would be rather tricky! The "traditional" way to do iteration uses a counter with a loop: $arr_size = count($array); for($i=0; $i<$arr_size; $i++) { $str = $array[$i]; } That's just one example which uses a variable index - not necessarily the clearest way to iterate over the array, but it makes its point!
October 14, 200917 yr Author Certainly is - otherwise iterating over the contents of an array would be rather tricky! The "traditional" way to do iteration uses a counter with a loop: $arr_size = count($array);for($i=0; $i<$arr_size; $i++) { $str = $array[$i];} That's just one example which uses a variable index - not necessarily the clearest way to iterate over the array, but it makes its point! Hey, thanks a lot! I'm slowly finding my feet with this PHP stuff
October 15, 200917 yr Just a quick note. With your original array you show $array=array(1=>"Cat",2=>"Dog",3=>"Rabbit",4=>"Mouse"); Since arrays work off numbers by default (incrementing by 1 each time) you could just use $array=array(1=>"Cat","Dog","Rabbit""Mouse"); and Dog, Rabbit and Mouse will automatically have the values 2, 3 and 4 respectively
Create an account or sign in to comment