boen_robot Posted May 24, 2007 Share Posted May 24, 2007 I need to remove a certain element in an array. The problem is it's position is unknown, so I can't simply call unset($array[0]) for example.I tryed looping with foreach and then check up on the members, like so: <?php function myFunction() { $array = array('a','b',4,7); foreach ($array as $member) { if ($member == 4) { unset($member); } } return $array; }print_r(myFunction());?> but that doesn't work. In the end, the array is still full. Removing the condition (hypothethically removing every $member) doesn't work either.So how exactly to remove an array member, leaving the members not matching the criteria alone?P.S. Damn. Arrays seem to be the most cumbersome thing to work with. I'm betting only SQL (in all of it's forms) could get more tricky in the simplest of situations.[edit]OK. The "for" loop seems to do the job. Still, could it be done with foreach somehow? It's just that I try to avoid "for". Call it a personal preference if you want.[/edit] Link to comment Share on other sites More sharing options...
vijay Posted May 25, 2007 Share Posted May 25, 2007 Hi.. for unset() u have to pass array element with ke like $arr[1] but u has passed value so.. it wont work... Replace your myfunction with follwoing.. you will get it.. function myFunction() { $array = array('a','b',4,7); foreach ($array as $key=>$val) { if ($val == 4) { unset($array[$key]); } } return $array; } Regards Vijay Link to comment Share on other sites More sharing options...
boen_robot Posted May 25, 2007 Author Share Posted May 25, 2007 Neat trick. Thanks. That actually also solved an issue that appeared shortly after I started testing with "for" (that alone should explain why am I trying to avoid it). Link to comment Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.