This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to check if an array element exists?
apologize if i am wrong,I am new to PHP, Is there any way to find out whether key exists in Json string after decoding using json_decode function in PHP.
$json = {"user_id":"51","password":"abc123fo"};
Brief:
$json = {"password":"abc123fo"};
$mydata = json_decode($json,true);
user_id = $mydata['user_id'];
If json string doesn't consist of user_id,it throws an exception like Undefined index user_id,so is there any way to check whether key exists in Json string,Please help me,I am using PHP 5.3 and Codeigniter 2.1 MVC Thanks in advance
IF you want to also check if the value is not null you can use isset
if( isset( $mydata['user_id'] ) ){
// do something
}
i.e. the difference between array_key_exists and isset is that with
$json = {"user_id": null}
array_key_exists will return true whereas isset will return false
You can try array_key_exists.
It returns a boolean value, so you could search for it something like:
if(array_key_exists('user_id', $mydata)) {
//key exists, do stuff
}
Related
This question already has answers here:
How to filter an array by a condition
(9 answers)
Closed 1 year ago.
I'm fairly new to PHP. I'm trying to filter out an array of items that contain a specific string. In order to then push those items to array, I need to pass the array to the function as a reference (or so my research has told me) however I can't seem to get it to work, any ideas? Thanks all.
$filteredS3Results = array();
function filterResults($var, &$filteredS3Results) {
if (strpos($var, '008-20160916') !== false) {
array_push($filteredS3Results, $var);
};
};
array_filter($s3Results,"filterResults");
The callback function just receives one argument, the array element being tested. It should return a boolean value that indicates whether the element should be included in the filtered result.
$filteredS3Results = array_filter($s3Results, "filterResults");
function filterResults($var) {
return strpos($var, '008-21060916') !== false;
}
This question already has answers here:
PHP in_array() / array_search() odd behaviour
(2 answers)
Closed 6 years ago.
It is known that in_array() function can be used to check if an array contains a certain value. However, when an array contains the value 0, an empty or null values pass the test, too.
For example
<?php
$testing = null;
$another_testing = 0;
if ( in_array($testing, [0,1,5,6,7]) )
echo "Found";
else
echo "Not Found";
echo "<br>";
if ( in_array($another_testing, [0,1,5,6,7]) )
echo "Found";
else
echo "Not Found";
?>
In both cases "Found" is printed. But I would like the first case to print "Not Found", and the second case - "Found".
I know I can solve the problem by adding an extra if statement, or by writing my own function, but I want to know if there are any built-ins in PHP that can perform the checks.
This behavior is explained by the fact that null == 0. But null !== 0. In other words, you should check for the types as well.
You don't need another function. Simply pass true as the third parameter:
in_array($testing, [0,1,5,6,7], true)
In this case in_array() will also check the types.
This question already has answers here:
php object attribute with dot in name
(5 answers)
Closed 7 years ago.
I have a json like the following
{"root":{
"version":"1",
"lastAlarmID":"123",
"proUser":"1",
"password":"asd123##",
"syncDate":"22-12-2014",
"hello.world":"something"
}
}
After json_decode(), I can get all the values except that of the last one hello.world, since it contain a dot.
$obj->root->hello.world doesn't work. I got solutions for doing it in Javascript but I want a solution in php.
$obj->root->{'hello.world'} will work.
ps: $obj->root->{hello.world} might not work.
b.t.w: Why not use Array? json_decode($json, true) will return Array. Then $a['root']['hello.world'] will always work.
You have two options here:
First option: convert the object to an array, and either access the properties that way, or convert the name to a safe one:
<?php
$array = (array) $obj;
// access the value here
$value = $array['hello.world'];
// assign a safe refernce
$array[hello_world] = &$array['hello.world'];
Second option: use quotes and brakets:
<?php
$value = $obj->root->{'hello.world'};
This is working
echo $test->root->{'hello.world'};
Check example
<?php
$Data='{"root":{
"version":"1",
"lastAlarmID":"123",
"proUser":"1",
"password":"asd123##",
"syncDate":"22-12-2014",
"hello.world":"something"}
}';
$test=json_decode($Data);
print_r($test);
echo $test->root->{'hello.world'};
?>
Output
something
You can use variable variables (http://php.net/manual/en/language.variables.variable.php):
$a = 'hello.world';
$obj->root->$a;
This question already has answers here:
What are the PHP operators "?" and ":" called and what do they do?
(10 answers)
Closed 7 years ago.
Could someone explain me the following line which is in the Symfony Cookbook (FYI the main topic is dynamic generation for Submitted Forms)
I don't undersand the following: ? , neither the array() :
$sport = $event->getData()->getSport(); // getdata submited by the user in the Sport input
$positions = null === $sport ? array() : $sport->getAvailablePositions();
// is it similaire to that line? what the difference?
$positions = $event->getData()->getSport()->getAvailablePositions();
? is a ternary if; which is an if statement on a single line.
It could be rewritten as
if (null === $sport) {
$positions = array(); // an empty array
} else {
$positions = $sport->getAvailablePositions();
}
The line says, if $sport is null (=== means check both type/value), $sport will be an empty array(), if not, $sport will be $sport->getAvailablePositions();
$positions just get the result of it!
This is called "Ternary Logic". You can check for a good article on this here: http://davidwalsh.name/php-shorthand-if-else-ternary-operators
The logic is:
Is $sport null?
If so, return an array
Otherwise, get the availablePosition collection
The goal is to have something iterable at the end and in all cases, like an array, a collection, etc.
It is not similar to $positions = $event->getData()->getSport()->getAvailablePositions(); because this will throw an error if getSport() returns null, thus calling getAvailablePosition() on something null.
It's a ternary condition operator. It's the factorisation of an if then followed by an affectation.Documentation
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Checking if an associative array key exists in Javascript
I have a PHP code block . For a purpose I am converting this to a JavaScript block.
I have PHP
if(array_key_exists($val['preferenceIDTmp'], $selected_pref_array[1]))
now I want to do this in jQuery. Is there any built in function to do this?
Note that objects (with named properties) and associative arrays are the same thing in javascript.
You can use hasOwnProperty to check if an object contains a given property:
o = new Object();
o.prop = 'exists'; // or o['prop'] = 'exists', this is equivalent
function changeO() {
o.newprop = o.prop;
delete o.prop;
}
o.hasOwnProperty('prop'); //returns true
changeO();
o.hasOwnProperty('prop'); //returns false
Alternatively, you can use:
if (prop in object)
The subtle difference is that the latter checks the prototype chain.
In Javascript....
if(nameofarray['preferenceIDTmp'] != undefined) {
// It exists
} else {
// Does not exist
}
http://phpjs.org/functions/array_key_exists:323
This is a great site for PHP programmers moving to js.