Returning Multiple Variables with isset() - php

I have a bit of code that returns the user agent, running it through a function to parse it. The code I have previously used returns only one variable from the parsing function (there are three: 'platform' 'browser' 'version'):
function my_get_user_agent($value)
{
$browser = parse_user_agent();
return isset($browser['platform']) ? $browser['platform'] : '';
}
While this code works to return the platform of the user agent, I need to append it to return all three variables in the function. I changed the first half of the code to what I assume is correct:
return isset($browser['platform'], $browser['browser'], $browser['version'])? $browser['platform'] : '';
I am unsure, however, as to what I need to do to properly return all three values. Suggestions?

You can just return the entire array:
return $browser;
Then access the values later:
$browser['platform'];
$browser['browser'];
$browser['version'];
Reading your question again, you seem to want to ensure the value are set. You can do this:
foreach($browser as $value) {
if(isset($value)) {
$data[] = $value;
}
}
return $data;
Now data will contain platform, browser, and version.

There is no tuple structure in PHP: Are there tuples in PHP?
You can either return the whole browser array, or a subset like this (this will not return the undefined values):
array_intersect_key($browser, array_flip(array("platform", "browser", "version")))
Also, if you want to set the result of your function to variables, the list construct can be handy, but you have to be sure that the values are in that order and that they exist. For that you would have to proceed like SeanWM suggested:
function my_get_user_agent($agent) {
$browser = parse_user_agent($agent);
foreach(array("platform", "browser", "version") as $value) {
$data[] = isset($browser[$value]) ? $browser[$value] : '';
}
return $data;
}
list($platform, $browser, $version) = my_get_user_agent($agent);

Related

PHP: Return the last json object

Edit
Thanks for all the input on this, I did find error in my question so modifying now. Sorry for that.
I am trying to figure out how to return the last object in the JSON string I have rendered. The two functions I am working with:
public function revision($return = false)
{
$id = $this->input->post('galleryID');
$data = array('revision_count' => $this->revision->count_revision($id) );
if($return){
return json_encode($data);
}
else {
echo json_encode($data);
}
}
public function last_revision()
{
$allRevisions = json_decode($this->revision(),true);
return end($allRevisions);
}
The issue is that end() returns error stating that 1st parameter should be array.
Thanks for any help on this.
It is important to note here that json_decode returns an instance of stdClass by default. Try using json_decode($jsonstring, true) to return the JSON as a PHP associative array.
However, You haven't included what the $this->revision() method does. Could you possibly show that portion of the code, since that is the function you are getting a return value from?
Edit:
Alright, after we saw the right function in your code, here are a couple of things I would like to say:
You have added a $return parameter to your revision method, but you aren't using it when you need to. You should change $this->revision() to $this->revision(true) in your last_revision method.
If you're going to return data from the revision() method, there's not much of a point in json_encodeing it, just to json_decode the result. Just pass back the raw data array.
Once you have changed both of these things, this should work:
$allRevisions = $this->revision(true); return end($allRevisions['revision_count']);
You can change the edit_function() to:
public function edit_revision($return = false)
{
$galleryID = $this->input->post('galleryID');
$revisionID = $this->input->post('revisionID');
$data = array('revision_images' => $this->revision->get($galleryID, $revisionID) );
if($return)
return json_encode($data);
else
echo json_encode($data);
}
and then:
public function last_revision(true)
{
$allRevisions = json_decode($this->revision());
return end($allRevisions);
}
Maybe you need convert that json output to an php array (json_decode() function), then you could get the last item with array_pop() function:
https://php.net/array_pop

PHP OOP newbie - Need to get $_POST data into a variable

I was basically playing around with OOP and was creating a way to validate and sanitise input when I started to run into problems sanitising and then performing further validation. What I'm looking for is to take the posted $_POST['name'] data, sanitise the input to remove any numbers and validate that the data left is neither null or numeric characters.
But I cant get the sanitised input saved to $sanitised, It seems to be empty, but when I replace
$sanitised=$fv->noNumbers($_POST['name']);
with
$sanitised=preg_replace('/[0-9]/', '', $_POST['name']);
everything works fine, so I think I'm messing up something in this $sanitised variable.
I wanna learn so either a solution to this or a "you're an idiot and doing it all wrong" would be much appreciated.
<?php
class formSanitise {
public function noNumbers($value) {
$value = preg_replace('/[0-9]/', '', $value);
}
public function isEmpty($value) {
return (!isset($value) || trim($value) == '') ? true : false;
}
public function isAlpha($value) {
return preg_match('/[^a-z]/i', $value) ? false : true;
}
?>
processor.php
<?php
include('class.formSanitise.php');
$fv = new formSanitise();
$sanitised= $fv->noNumbers($_POST['name']);
if ($fv->isEmpty($sanitised)) {
$fv->addError('Name', 'Please enter something');
}
if (!$fv->isAlpha($sanitised)) {
$fv->addError('Name', 'Please enter your name');
}
?>
You'll either need to create a return in noNumbers or pass $value by reference.
Return method:
public function noNumbers($value) {
return preg_replace('/[0-9]/', '', $value);
}
Reference
public function noNumbers(&$value) {
$value = preg_replace('/[0-9]/', '', $value);
}
returning a value means that $value is an entirely different variable, and will be assigned to $sanitized when it's returned from the function. Passing by reference means that $value is the exact same variable as the one you passed to noNumbers and as such, anything that happens to the variable inside the function will happen to the variable that has been passed in.
In the above code snippet the function noNumbers does not return any value.The argument passed to the function has a scope within that function only and in order to make that value available to calling function there must be a return statement within function which will return the value to the calling function .Alternatively you can pass the value to function by reference .

PHP newbie question: return variable with function?

i've been coding asp and was wondering if this is possible in php:
$data = getData($isEOF);
function getData($isEOF=false)
{
// fetching data
$isEOF = true;
return $data;
}
the function getData will return some data, but i'd like to know - is it possible to also set the $isEOF variable inside the function so that it can be accessed from outside the function?
thanks
It is possible, if your function expects it to be passed by reference :
function getData(& $isEOF=false) {
}
Note the & before the variable's name, in the parameters list of the function.
For more informations, here's the relevant section of the PHP manual : Making arguments be passed by reference
And, for a quick demonstration, consider the following portion of code :
$value = 'hello';
echo "Initial value : $value<br />";
test($value);
echo "New value : $value<br />";
function test(& $param) {
$param = 'plop';
}
Which will display the following result :
Initial value : hello
New value : plop
Using the global statement you can use variables in any scope.
$data = getData();
function getData()
{
global $isEOF;
// fetching data
$isEOF = true;
return $data;
}
See http://php.net/manual/en/language.variables.scope.php for more info.
Yes, you need to pass the variable by reference.
See the example here : http://www.phpbuilder.com/manual/functions.arguments.php

What does & before the function name signify?

What does the & before the function name signify?
Does that mean that the $result is returned by reference rather than by value?
If yes then is it correct? As I remember you cannot return a reference to a local variable as it vanishes once the function exits.
function &query($sql) {
// ...
$result = mysql_query($sql);
return $result;
}
Also where does such a syntax get used in practice ?
Does that mean that the $result is returned by reference rather than by value?
Yes.
Also where does such a syntax get used in practice ?
This is more prevalent in PHP 4 scripts where objects were passed around by value by default.
To answer the second part of your question, here a place there I had to use it: Magic getters!
class FooBar {
private $properties = array();
public function &__get($name) {
return $this->properties[$name];
}
public function __set($name, $value) {
$this->properties[$name] = $value;
}
}
If I hadn't used & there, this wouldn't be possible:
$foobar = new FooBar;
$foobar->subArray = array();
$foobar->subArray['FooBar'] = 'Hallo World!';
Instead PHP would thrown an error saying something like 'cannot indirectly modify overloaded property'.
Okay, this is probably only a hack to get round some maldesign in PHP, but it's still useful.
But honestly, I can't think right now of another example. But I bet there are some rare use cases...
Does that mean that the $result is returned by reference rather than by value?
No. The difference is that it can be returned by reference. For instance:
<?php
function &a(&$c) {
return $c;
}
$c = 1;
$d = a($c);
$d++;
echo $c; //echoes 1, not 2!
To return by reference you'd have to do:
<?php
function &a(&$c) {
return $c;
}
$c = 1;
$d = &a($c);
$d++;
echo $c; //echoes 2
Also where does such a syntax get used in practice ?
In practice, you use whenever you want the caller of your function to manipulate data that is owned by the callee without telling him. This is rarely used because it's a violation of encapsulation – you could set the returned reference to any value you want; the callee won't be able to validate it.
nikic gives a great example of when this is used in practice.
<?php
// You may have wondered how a PHP function defined as below behaves:
function &config_byref()
{
static $var = "hello";
return $var;
}
// the value we get is "hello"
$byref_initial = config_byref();
// let's change the value
$byref_initial = "world";
// Let's get the value again and see
echo "Byref, new value: " . config_byref() . "\n"; // We still get "hello"
// However, let’s make a small change:
// We’ve added an ampersand to the function call as well. In this case, the function returns "world", which is the new value.
// the value we get is "hello"
$byref_initial = &config_byref();
// let's change the value
$byref_initial = "world";
// Let's get the value again and see
echo "Byref, new value: " . config_byref() . "\n"; // We now get "world"
// If you define the function without the ampersand, like follows:
// function config_byref()
// {
// static $var = "hello";
// return $var;
// }
// Then both the test cases that we had previously would return "hello", regardless of whether you put ampersand in the function call or not.

Is there a better way to check POSTed variables in PHP?

I find in my PHP pages I end up with lines and lines of code that look like this:
$my_id = isset($_REQUEST['my_id']) ? $_REQUEST['my_id'] : '';
$another_var = isset($_REQUEST['another_var']) ? $_REQUEST['another_var'] : 42;
...
Is there a better, more concise, or more readable way to check this array and assign them to a local variable if they exist or apply a default if they don't?
EDIT: I don't want to use register_globals() - I'd still have the isset problem anyway.
How about wrapping it in a function?
<?php
function getPost($name, $default = null) {
return isset($_POST[$name]) ? $_POST[$name] : $default;
}
a better method might be to create a singleton/static class to abstract away the details of checking the request data.
Something like:
class Request {
private $defaults = array();
private static $_instance = false;
function getInstance () {
if (!self::$_instance) {
$c = __CLASS__;
self::$_instance = new $c;
}
return self::$_instance;
}
function setDefaults($defaults) {
$this->defaults = $defaults;
}
public function __get($field) {
if (isset($_REQUEST[$field]) && !empty($_REQUEST[$field])) {
return $_REQUEST['field'];
} elseif (isset($this->defaults[$field])) {
return $this->defaults[$field];
} else {
return ''; # define a default value here.
}
}
}
you can then do:
# get an instance of the request
$request = Request::getInstance();
# pass in defaults.
$request->setDefaults(array('name'=>'Please Specify'));
# access properties
echo $request->name;
echo $request->email;
I think this makes your individual scripts loads cleaner and abstracts away the validation etc. Plus loads of scope with this design to extend it/add alternate behaviours, add more complicated default handling etc etc.
First, use $_POST for POSTed variables. $_REQUEST is a mashup of many different incoming variables, not just $_POST and could cause problems.
One solution for your question would be to create a function that handles the isset() logic.
function ForceIncomingValue($Key, $Default) {
if (!isset($_POST[$Key]))
return $Default;
else return $_POST[$Key];
}
first of all, NEVER use the $_REQUEST variable, it'll lead to bugs and other problems during development
function getPOST($key) {
if(isset($_POST[$key])) {
return $_POST[$key];
}
}
note that this code leaves the variable empty when $_POST[$key] was not set
you could also adapt that code to enable you to instead provide you with a (sensible) default when the value could not be loaded.
function getPOST($key, $default = NULL) {
if(isset($_POST[$key])) {
return $_POST[$key];
} else {
return $default;
}
}
Is the set of variables you're expecting known at the time of the script's writing, or do you want to do this for an arbitrary set of values? If the former is true, you could do something like this:
# This array would hold the names of all the variables you're expecting
# and a default value for that variable name
$variableNames = array (...);
foreach ($variableNames as $key => $default) {
if (isset ($_REQUEST[$key])) $$key = $_REQUEST[$key];
else $$key = $default;
}
Basically, this takes advantage of PHP's ability to evaluate variables to create other variables (hence the double-dollar for $$key--this means create a new variable whose name is the value of $key).
I haven't yet come up with a good solution to the latter situation.
PHP's null coalescing operator!
$username = $_GET['user'] ?? 'nobody';
For a lot of variables, with a requirement check, anyone is free to use my expect function.

Categories