I am using this shorthand in a function to set a variable to NULL if it is not set. How can I simply not set it?
function createArray($rows){
$array = array();
$array['id'] = isset($rows['UnitId']) ? $rows['UnitId'] : NULL ;
}
Would this be too simple for you?
if(isset($rows['UnitId'])) {
$array['id'] = $rows['UnitId'];
}
Just don't set it in the first place
function createArray($rows){
$array = array();
if(isset($rows['UnitId'])) $array['id'] = $rows['UnitId'];
}
Related
In PHP we can do things like these:
Class Example {
...
}
$example = 'Example';
$object = new $example();
Or the use of variable variables:
$hour = 18;
$greets = array('Good morning','Good afternoon','Good evening');
$values = array(13,21,23);//people is sleeping at 23PM, so they don't greet.
$n = count($values);
$greet = 'greets';
for($i=0;$i<$n;$i++){
if($hour < $values[$i]){
echo 'hello, '.${$greet}[$i];
break;
}
}
And others..
I wonder if it would be possible to access directly to a specific index of a multidimensional array in a similar way. Something like:
$array = array(...); //multidimensional array.
$position = '[0][4][3]';
print_r($array$position);
Thanks in advance.
UPDATE
I'm so sorry because I finished my question in a wrong way.
I need to set the multimesional array and add a value. i.e:
$array$position = $data;
You could implement it yourself with a custom function:
function getValueFromMultiDimensionalArray( array $array, string $key )
{
$keys = explode('][', $key);
$value = $array;
foreach ($keys as $theKey) {
// remove the opening or closing bracket if present
$theKey = str_replace([ '[', ']' ], '', $theKey);
if (!isset($value[$theKey])) {
return null;
}
$value = $value[$theKey];
}
return $value;
}
You can define path as dot separated , check the following solution
function getValueByKey($a,$p){
$c = $a;
foreach(explode('.',$p) as $v){
if(!array_key_exists($v, $c)) return null;
$c = $c[$v];
}
return $c;
}
You can use this function as
$path = '1.2.3.0';
$indexValue = getValueByKey($array, $path);
Nope, this is not possible.
The only thing you can do is to implement ArrayAccess interface, which allows to access instances with [] operator. But you will have to define the logic yourself.
class MyClass implements ArrayAccess
{
...
}
$x = new MyClass([0=>[4=>[3=>'hello world']]]);
$position = '[0][4][3]';
echo $x[$position]; //hello world
Consider this code:
$var = 'test';
$_POST[$test]; // equals $_POST['test']
How can I access with the same method this variable:
$_POST['test'][0];
$var = 'test[0]'; clearly doesn't work.
EDIT
Let me give a bit more information. I've got a class that builds a form.
An element is added like this:
//$form->set_element(type, name, defaultValue);
$form->set_element('text', 'tools', 'defaultValue');
This results into :
<input type="text" name="tools" value="defaultValue" />
In my class I set the value: if the form is posted, use that value, if not, use the default:
private function set_value( $name, $value='' ) {
if( $_SERVER['REQUEST_METHOD'] == 'POST' )
return $_POST[$name];
else
return $value;
}
When I want to add multiple "tools", I would like to use:
$form->set_element('text', 'tools[0]', 'defaultValue');
$form->set_element('text', 'tools[1]', 'defaultValue');
$form->set_element('text', 'tools[2]', 'defaultValue');
But in the set_value function
that gives $_POST['tools[0]'] instead of $_POST['tools'][0]
Use any number of variables in [] to access what you need:
$test = 'test';
$index = 0;
var_dump($_POST[$test][$index]);
$test = 'test';
$index = 0;
$subkey = 'key'
var_dump($_POST[$test][$index][$subkey]);
And so on.
There's no special function to achieve what you want, so you should write something, for example:
$key = 'test[0]';
$base = strstr($key, '[', true); // returns `test`
$ob_pos = strpos($key, '[');
$cb_pos = strpos($key, ']');
$index = substr($key, $ob_pos + 1, $cb_pos - $ob_pos - 1);
var_dump($arr[$base][$index]);
Edit by LinkinTED
$key = 'test[0]';
$base = $n = substr($name, 0, strpos($key, '[') );
preg_match_all('/\[([^\]]*)\]/', $key, $parts);
var_dump($arr[$base][$parts[1][0]]);
See how when you did $_POST['test'][0]; you just added [0] to the end? As a separate reference.
You have to do that.
$_POST[$test][0];
If you need both parts in variables then you need to use multiple variables, or an array.
$var = Array( "test", "0" );
$_POST[$test[0]][$test[1]];
Each dimension of an array is called by specifying the key or index together with the array variable.
You can reference a 3 dimensional array's element by mentioning the 3 indexes of the array.
$value = $array['index']['index']['index'];
Like,
$billno = $array['customers']['history']['billno'];
You can also use variables which has the index values that can be used while specifying the array index.
$var1 = 'customers';
$var2 = 'history';
$var3 = 'billno';
$billno = $array[$var1][$var2][$var3];
Is it possible to set a variables value from a $_GET['var'] doing somthing like this:
if( $foo = isset($_GET['foo']) ) // Or something close to this.
I.e if $_GET['foo'] is set assign it's value then and there
instead of this like I currently do
if( isset($_GET['foo']) )
$foo = $_GET['foo'];
This is ok when it's just one or two, but like me when you have 10+ $_GET's it gets ugly.
user ternary operator
$foo = isset($_GET['foo']) ? $_GET['foo'] : "";
try
$foo = !empty($_GET['foo']) ? $_GET['foo'] : null;
No, this is not possible. You can do it in shorthand with a ternary statement, but that's not a great deal less clunky.
The best you can do might be to write a function like the following:
function extractFromGet(array $keys) {
$ret = []; // empty array
foreach ($keys as $key) {
$ret[$key] = isset($_GET[$key]) ? $_GET[$key] : null;
}
return $ret;
}
You can then call it as follows:
list ($name, $email, $telephone, $address) = extractFromGet(
['name', 'email', 'telephone', 'address']
);
I would like to assign a variable that is the first not null element from another set of variables. Much like the conditional assignment in ruby ||=. For example:
<?php
$result = null;
$possibleValue1 = null;
// $possibleValue2 not defined
$possibleValue3 = 'value3';
if (isset($possibleValue1) && !is_null($possibleValue1)) {
$result = $possibleValue1;
} else if (isset($possibleValue2) && !is_null($possibleValue2)) {
$result = $possibleValue2;
} else if (isset($possibleValue3) && !is_null($possibleValue3)) {
$result = $possibleValue3;
}
Is there a way to do this simply in php, like so (if possible, I would like to avoid creating a function and just use functions from the php library):
$result = firstNotNull(array($possibleValue1, $possibleValue2, $possibleValue3));
I think the shortest way is:
$result = current(array_filter(array($possibleValue1, $possibleValue2, $possibleValue3)));
If all $possibleValues are definitely set:
$possibleValues = array($possibleValue1, $possibleValue2, ...);
If they may not be set:
$possibleValues = compact('possibleValue1', 'possibleValue2', ...);
Then:
$result = reset(array_filter($possibleValues, function ($i) { return $i !== null; }));
Do not know about such a function in PHP but why not creating Your own?
function getFirstNotNullValue($values = array()) {
foreach($values as $val)
if($val) return $val;
return false;
}
hmm i got a homework, its 2 hours and i still have no clue on it :|
like this
$sessions['lefthand'] = 'apple';
$sessions['righthand'] = '';
$sessions['head'] = 'hat';
$sessions['cloth'] = '';
$sessions['pants'] = '';
// here is the homework function
CheckSession('lefthand,righthand,head,cloth,pants');
we have some string "lefthand,righthand,head,cloth,pants"
question is : " how can we check if the five session is not null or exist and display which session is empty ( if there is an empty session ) if all exist then returns a true ?
empty righthand , pants, and cloth.
this is how i think about it
explode it to arrays
check one bye one if !null id there is a
here is the progress that ive made *edit4 , :)
function CheckSession($sessions){
$all_sessions_exist = true;
$keys = explode(',',$sessions);
$error = array();
// Search for Session that are not exist
foreach ($keys as $key) {
if (!isset($_SESSION[$key]) && empty($_SESSION[$key])) {
echo "no $key</br>";
$all_sessions_exist = false;
}
}
return $all_sessions_exist;
}
Thanks for taking a look
Adam Ramadhan
Seeing as it's homework, you won't get the solution. You're on the right track though. explode() it by the delimiter. You can the loop through it using foreach and use empty() to check if they're set. You can access the sessions like $_SESSION[$key]. Keep an array of the ones that match.
function CheckSession($string){
$all_sessions_exist = true; #this will change if one of the session keys does not exist
$keys = explode(',', $string); #get an array of session keys
foreach($keys as $key){
if(isset($_SESSION[$key])) {
if(!empty($_SESSION[$key]))
echo '$_SESSION['.$key.'] is set and contains "'.$_SESSION[$key].'".'; #existing non-empty session key
else echo '$_SESSION['.$key.'] is set and is empty.' ;
}else {
echo '$_SESSION['.$key.'] is not set.'; #key does not exist
$all_sessions_exist = false; #this will determine if all session exist
}
echo '<br />'; #formatting the output
}
return $all_sessions_exist;
}
Just cleaning up your function
function CheckSession($sessions)
{
$session = explode(',',$sessions);
$return = array();
foreach ($session as $s)
{
$return[$s] = (isset($_SESSION[$s]) && !empty($_SESSION[$s]) ? true : false)
}
return $return;
}
$sessions['lefthand'] = 'apple';
$sessions['righthand'] = '';
$sessions['head'] = 'hat';
$sessions['cloth'] = '';
$sessions['pants'] = '';
And the checking part
// here is the homework function
$Results = CheckSession('lefthand,righthand,head,cloth,pants');
Edit
//$value1= false; // Commented out so does not get set
$value2= false; //Still set to a bool
error_reporting(E_ALL);
empty($value1); // returns false but still strikes E_NOTICE ERROR
empty($value2); // returns false with no error
Note, empty does not trigger an error but this example would take affect an a lot of other php functions.