How can I get $_GET values to a variable - php

In my page, there are multiple $_GET values. ie
if(isset($_GET["projects"]))
{ ..... }
else if(isset($_GET["research"]))
{ ...... }
else if(isset($_GET["publication"]))
{ ..... }
...upto 10 elseif's
Can I shorten this?
Can I get these values {projects,research, publication,..} in a variable.?

Ok so I guess I figured out what you want from your comments. Lets see.
$types = array('projects', 'research', 'publication'); // add as many as you want
$valid = array_intersect_key($_GET, array_flip($types));
if (count($valid) > 1)
die "More than one category is set, this is invalid.";
if (!$valid)
die "No category was set, you must choose one.";
foreach ($valid as $type => $value) // just to split this one element array key/value into distinct variables
{
$value = mysql_real_escape_string($value); // assuming you are using mysql_*
$sql = "SELECT * FROM table WHERE $type = '$value'";
}
...

Yes, you can assign these in a variable -
if(isset($_GET["projects"]))
{
$value = $_GET['projects'];
}
else if(isset($_GET["research"]))
{
$value = $_GET['research'];
}
else if(isset($_GET["publication"]))
{
$value = $_GET['publication'];
}
echo $value;

I'm guessing you're expecting a single value in $_GET, like ?projects=foo or ?research=bar. In that case:
$type = key($_GET);
$value = $_GET[$type];
echo "$type = $value";

$projects = $_GET["projects"];
Or just use directly from $_GET, this is an associative array with all the values.
foreach ($_GET as $key => $value){
if(!empty($value)){
$type = $key; //if you expect a single item
$type[] = $key; //if you expect multiple items
}
}

if the intent is to check if values on a form have been answered/filled out you could use
if(isset($_GET['project'] || ... || isset($_GET['publication'])
{
// Insert Code Here
}
else
{
// Insert Code Here
}
The above code is assuming the fields are not text fields or textareas if those are the types of inputs then instead of
if(isset($_GET['project']))
use
if($_GET['project'] != "")

I didn't completely understood what you are saying but looks like that you are trying to execute something when all $_GET is true. If so then use the code below
if(isset($_GET["projects"]) && isset($_GET["research"]) && isset($_GET["publication"]) )
{ ..... }
Hope this helps you

Related

Dynamic condition with values in the array

I want to generate a dynamic condition with values in the array $unique_keys
$unique_keys = array('name', 'phone');
And the result in PHP will be :
if($search_array['name'] == $current_array['name'] && $search_array['phone'] == $current_array['phone']){
// some code
}
The only way i know it's a foreach and an eval, but there's no cleaner way, something likes Variable variables ?
Why you need eval or variable variables? You can use just key names.
$unique_keys = array('name', 'phone');
...
$good = true;
foreach ($unique_keys as $k) {
if ($search_array[$k] != $current_array[$k]) {
$good = false;
break;
}
}
if ($good) {
// Found!
} else {
// No luck
}

Check if object/array is empty

I'm trying to check if the following is empty or not.
{"players":""}
I have a function that gets that from an api/site and.. well, heres the code.
function getPlayers($server) {
// Fetches content from url and json_decodes it
$playersList = getUrl('http://api.iamphoenix.me/list/?server_ip=' . $server);
// Attempting to check if it's empty.
if ($playersList != "") {
// convert list of comma-separated names into array
$players = explode(',', $playersList->players);
foreach ($players as $player) {
echo '<img title="'.$player.'" src="https://minotar.net/avatar/'.$player.'/32">';
}
} else {
return 'empty';
}
}
However, using !=, empty(), or isset(), I still get an empty string, example:
https://minotar.net/avatar//32
Where it should be..
https://minotar.net/avatar/Notch/32
When it's empty, I'd like it to just return 'empty'.
I'm not sure what I'm doing wrong. Any ideas?
In pure php you can check the url segments like
$_SERVER['REQUEST_URI_PATH'] = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$segments = explode('/', $_SERVER['REQUEST_URI_PATH']);
if($segments[2] == '') {
}
//or
if(empty($segments[2])) {
}
//or do your condition
if you are using codeigniter you might say
if(empty($this->uri->segment(2)))
But be sure you loaded the url helper
Hope I understand your question!
Since you were able to have some output, see my changes in the codes.
function getPlayers($server) {
// Fetches content from url and json_decodes it
$playersList = getUrl('http://api.iamphoenix.me/list/?server_ip=' . $server);
// Attempting to check if it's empty.
if ($playersList != "") {
// convert list of comma-separated names into array
$players = explode(',', $playersList->players);
// check conversion
if(is_array($players) && !empty($players){
foreach ($players as $player) {
echo '<img title="'.$player.'" src="https://minotar.net/avatar/'.$player.'/32">';
}
} else {
return 'empty';
}
} else {
return 'empty';
}
}
You should do this;
print_r($playersList);
just after you set it to see what it actually is. My guess is that you are not getting what you suspect from the getURL call.
Add one more equals sign to take type comparison into account as well
if ($playerList !== '')
try this
if (isset($playersList) && is_array($playersList) && !empty($playersList)) {
// convert list of comma-separated names into array
$players = explode(',', $playersList->players);
foreach ($players as $player) {
echo '<img title="'.$player.'" src="https://minotar.net/avatar/'.$player.'/32">';
}
} else {
return 'empty';
}

Form processing $_POST to variables automatically

I have about 40 items in my FORM and i'm trying to give all the Name= properties a variable for process without having to write each out manually. am I missing something here, cause the code below is not working. (name="comp1", name="comp2"... $comp1, $comp2)
$en = array_merge($em, $_POST);
$valid = true;
foreach($_POST as $value) {
if(!isset($value)) {
$valid = false;
}
}
If something is not in $_POST, the foreach will not loop through it. Isset() will always return true, because the foreach loops through all values in $_POST.
foreach($_POST as $k=>$val) {
//$$k = $val;
if(!isset($$k)){
echo "==NO==";
}
}
the POST will always be set, unless you disable the field with something like this:
<input disabled="disabled"/>
If the filds doesn't have this attribute, the only way to check if the field was filled is a comparse with an empty string, with $value == '' this way:
foreach($_POST as $key => $value) {
if($value == '') {
$valid[$key] = false;
}else{
$valid[$key] = true;
}
}
You will have now an array ($valid) that will look like:
var_dump($valid['field1']); //prints true, the field was filled
var_dump($valid['field2']); //prints false, the field was NOT filled

PHP If statements and Arrays

I have an array
$results = array(101, 102, 103, 104, 105)
I also have a input field where the user enters a number
<input type ="text" name="invoice" />
I put what the number that user enters in, into a variable
$id = $_POST['invoice']
How would I write an if statement to check to see if the number that user entered is in that array
I have tried doing in a for each loop
foreach($result as $value){
if($value == $id){
echo 'this';
}else{
continue;
}
is there a better way of doing this?
if (in_array($id, $results)) {
// ...
}
http://php.net/manual/en/function.in-array.php
Use in_array():
if (in_array($_POST['invoice'], $your_array)) {
... it's present
}
ok you can try this:
if ( in_array($id, $results))
{
// execute success
}
else
{
// execute fail
}
You can use in_array, like the others have suggested
if(in_array($id,$results)) {
//do something
} else {
$no_invoice = true;
}
but if you happen to want to use your array key for anything, you can kill two birds with one stone.
if($key = array_search($id,$results,true)) {
echo 'You chose ' . $results[$key] . '<br />';
}
Obviously for echoing you don't need my method - you could just echo $id - but it's useful for other stuff. Like maybe if you had a multi-dimensional array and element [0]'s elements matched up with element[1]'s elements.
If you are looking to compare values of one array with values of another array in sequence then my code is really simple: check this out it will work like this:
if (1st value of array-1 is equal to 1st value of array-2) { $res=$res+5}
if($_POST){
$res=0;
$r=$_POST['Radio1']; //array-1
$anr=$_POST['answer']; //array-2
$arr=count($r);
for($ac=0; $ac<$arr; $ac++){
if($r[$ac]==$anr[$ac]){
$res=$res+5;
}
}
echo $res;
}
Not quite.
your way is good enough, it only needs to be corrected.
foreach($results as $value){
if($value == $id){
echo 'this';
break;
}
}
is what you really wanted

collecting multiple GET or POST values

I have a form that passes something like in a URL
?choice=selection+A&choice=selection+C
I'm collecting it in a form with something like (I remember that $_GET is any array)
$temp = $_GET["choice"];
print_r($temp);
I'm only getting the last instance "selection C". What am I missing
I am assuming 'choice' is some kind of multi-select or checkbox group? If so, change its name in your html to 'choice[]'. $_GET['choice'] will then be an array of the selections the user made.
If you don't intend to edit the HTML, this will allow you to do what you're looking to do; it will populate the $_REQUEST superglobal and overwrite its contents.
This assumes PHP Version 5.3, because it uses the Ternary Shortcut Operator. This can be removed.
$rawget = isset($_SERVER['QUERY_STRING']) ? $_SERVER['QUERY_STRING'] : false;
$rawpost = file_get_contents('php://input') ?: false;
$target = $rawget;
$_REQUEST = array();
if ($target !== false) {
$pairs = explode('&',$rawget);
foreach($pairs as $pair) {
$p = strpos($pair,'=');
if ($p === false && !empty($pair)) {
$_REQUEST[$pair] = null;
}
elseif ($p === 0 || empty($pair)) {
continue;
}
else {
list($name, $value) = explode('=',$pair,2);
$name = preg_replace('/\[.*\]/','',urldecode($name));
$value = urldecode($value);
if (array_key_exists($name, $_REQUEST)) {
if (is_array($_REQUEST[$name])) {
$_REQUEST[$name][] = $value;
}
else {
$_REQUEST[$name] = array($_REQUEST[$name], $value);
}
}
else {
$_REQUEST[$name] = $value;
}
}
}
}
As it stands, this will only process the QueryString/GET variables; to process post as well, change the 3rd line to something like
$target = ($rawget ?: '') . '&' . ($rawpost ?: '');
All that having been said, I'd still recommend changing the HTML, but if that's not an option for whatever reason, then this should do it.

Categories