charles07 Posted April 11, 2012 Share Posted April 11, 2012 guys plz help, i have an array(52,51,52) here i want to insert first & last elements into DB, not second one does not follows the series another array (52,52,53) in this case insert first 2 elements into DB since last element does not follow the series. how is this possible? Quote Link to comment https://forums.phpfreaks.com/topic/260746-remove-odd-datas-from-array/ Share on other sites More sharing options...
xyph Posted April 11, 2012 Share Posted April 11, 2012 <?php $array = array(40,43,66); foreach( $array as $key => $value ) { if( $value % 2 != 0 ) { unset($array[$key]); } } print_r( $array ); ?> http://php.net/manual/en/language.operators.arithmetic.php Quote Link to comment https://forums.phpfreaks.com/topic/260746-remove-odd-datas-from-array/#findComment-1336384 Share on other sites More sharing options...
Andy-H Posted April 11, 2012 Share Posted April 11, 2012 version > PHP 5.3 $array = array_filter($array, function($var) { return !($var % 2); }); version < PHP5.3 $array = array_filter($array, create_function('$var', 'return !($var % 2);')); Unless you mean odd one out as opposed to odd number? I just assumed not because in sequence 52, 51 the next would be 50 but you stated you wanted first and last (both 52) Quote Link to comment https://forums.phpfreaks.com/topic/260746-remove-odd-datas-from-array/#findComment-1336468 Share on other sites More sharing options...
algidDes702 Posted April 11, 2012 Share Posted April 11, 2012 without fully understanding the context of the data you are trying to process and what a 'series' is. What i got from your question is that you need anything/number that is 52 to be processed, anything else to be left out. The first reply was a great way to do so unless in the future you had an even number such as 56 in your array that you didnt want to process/add when you only wanted the 52 'series'. <?php $seriesNum = 52; //could be whatever number you want to add, can also be retrieved from a data source somewhere else rather than hardcoded $array = array(52,53,52,56,65,234,45,52); //array with odd and even numbers foreach( $array as $key => $value ) { if( $value != $seriesNum ) { //set the test to your series number, a modulus operator would return even numbers that aren't 52 series in your ex. unset($array[$key]); } } $array = array_values($array); //this line re-indexes the returned array starting from 0 array (optional, not needed for your question) print_r( $array ); ?> Hope this helped along with the other's replies! Thanks! Quote Link to comment https://forums.phpfreaks.com/topic/260746-remove-odd-datas-from-array/#findComment-1336536 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.