Reputation: 3560
i need one help.i need to remove those ids which has also some letters and inserted rest into a array using PHP. i am explaining my code below.
http://oditek.in/spesh/mobileapi/categoryproduct.php?item=1&acn=5&subcat_id=a15,15,16
here in subcat_id
i have one id a15
i need to remove this type of ids wheile comes and rest should insert into a array.Please help me.
Upvotes: 0
Views: 58
Reputation: 1022
Try preg_replace for getting numeric ids
$subcatid = explode(",",$_GET['subcat_id']);
$arrId = [];
foreach($subcatid AS $id) {
$arrId[] = preg_replace("/[^0-9]/", "", $id);
}
var_dump($arrId); //$arrId contains all the numeric IDs only
Upvotes: 0
Reputation: 1981
Try this:
$url = 'http://oditek.in/spesh/mobileapi/categoryproduct.php?item=1&acn=5&subcat_id=a15,15,16';
$parts = parse_url($url);
$q = array();
parse_str($parts['query'], $q);
$subcatIds = explode(',', $q['subcat_id']);
$subcatIds = array_map(function($element){ return filter_var($element, FILTER_SANITIZE_NUMBER_INT);}, $subcatIds);
print_r($subcatIds);
Result is:
Array ( [0] => 15 [1] => 15 [2] => 16 )
Working example: CLICK!
So basically, if you have subcat_id
in $_GET
, then you need only two lines:
$subcatIds = explode(',', $_GET['subcat_id']);
$subcatIds = array_map(function($element){ return filter_var($element, FILTER_SANITIZE_NUMBER_INT);}, $subcatIds);
Upvotes: 0
Reputation: 531
if you are not getting the URL from the request you would have to parse it first.
<?php
$url = "http://oditek.in/spesh/mobileapi/categoryproduct.php?item=1&acn=5&subcat_id=a15,15,16";
$query_str = parse_url($url, PHP_URL_QUERY);
parse_str($query_str, $query_params);
$ids = explode(",",$query_params['subcat_id']);
print_r($ids);
foreach( $ids as $index => $id){
if( is_numeric($id) === false ){
unset($ids[$index]);
}
}
print_r($ids);
?>
The for loop in my example could be replaced by array_filter($ids, 'is_numeric') like in jszobody answer.
Upvotes: 0
Reputation: 28941
If I understand you correctly, you want to take the string a15,15,16
, convert to an array, and remove the non-numeric values?
If so, it's pretty simple:
$subcatArray = explode(',', $_GET['subcat_id']);
$subcatArrayNumeric = array_filter($subcat, 'is_numeric');
Now $subcatArrayNumeric
will be an array with '15' and '16' in it, only.
Working example: https://3v4l.org/hWSOj
Upvotes: 2