Reputation: 17
Currently I have this code that stores all $_GET requests:
$array_name = array();
foreach ($_GET as $key => $value) {
$array_name[] = "'%".escape_string($value)."%'";
}
My goal is to somehow only store certain values, if for example I have 5 different $_GET request, named 1,2,3,4 and 5. I only want to store 1-3 in this array. How would this be possible?
Upvotes: 0
Views: 86
Reputation: 93
Slightly different approach to the other answers. $keysToStore
is an array of the keys you want to store.
The foreach loop then pulls these values from the $_GET
array rather than looping the entire array.
$keysToStore = [1, 2, 3];
$array_name = [];
foreach ( $keysToStore as $key ) {
$array_name[] = "'%" . escape_string( $_GET[$key] ) . "%'";
}
Edit: can check isset
inside the loop if keys are not validated elsewhere.
$keysToStore = [1, 2, 3];
$array_name = [];
foreach ( $keysToStore as $key ) {
if ( isset( $_GET[$key] ) ) {
$array_name[] = "'%" . escape_string( $_GET[$key] ) . "%'";
}
}
Upvotes: 0
Reputation: 87
For this, you need to add check on $key, that $key has value 1 or 2 or 3. Sample code is this:
$array_name = array();
foreach ($_GET as $key => $value) {
if($key == '1' || $key == '2' || $key == '3'){
$array_name[] = "'%".escape_string($value)."%'";
}
}
Or the other sample code is:
$array_name = array();
foreach ($_GET as $key => $value) {
if(in_array($key, array(1, 2, 3))){
$array_name[] = "'%".escape_string($value)."%'";
}
}
Here 1 , 2 and 3 is key of $_GET. Sample input is: $_GET['1'] = 'Ghazal' , $_GET['2'] = 'Taimur' , $_GET['3'] = 'Malik' , $_GET['4'] = 'Test' , $_GET['5'] = 'City'
Upvotes: -1
Reputation: 78994
You can get the intersection of an array of keys you want:
foreach(array_intersect_key($_GET, array_flip([1,2,3])) as $value) {
$array_name[] = "'%".escape_string($value)."%'";
}
Upvotes: 1
Reputation: 488
$array_name = array();
foreach ($_GET as $key => $value) {
if(in_array($key, array(1, 2, 3)))
$array_name[] = "'%".escape_string($value)."%'";
}
}
It this what you are looking for?
Upvotes: 2