Check array values in another array variable [duplicate] - php

This question already has answers here:
Checking if ANY of an array's elements are in another array
(8 answers)
Closed 9 months ago.
I have 2 php array variables. Variables like below.
$arrIntPropertyIds = [ 1,2,3,4,5,6,7,8,9,10];
$arrIntRequestPropertyIds = [ 3, 5, 7];`
I want to check whether values of $arrIntRequestPropertyIds are in $arrIntPropertyIds without loop.
So I tried like below.
if( count(array_diff($arrIntPropertyIds,$arrIntRequestPropertyIds))==0 ) {
echo 'invalid property Id';
} else {
echo 'Valid property Id';
}
If all OR any of the value OR atleast 1 value is/are there in first array then it should show message 'invalid'.

All you have to do is change the order in which you present the arrays to the array_diff() function and then change the if accordingly
$arrIntPropertyIds = [ 1,2,3,4,5,6,7,8,9,10];
$arrIntRequestPropertyIds = [ 3, 5, 7];
if( count(array_diff($arrIntRequestPropertyIds, $arrIntPropertyIds))==0 ) {
echo 'Valid property Id';
} else {
echo 'invalid property Id';
}

Use array_diff. Simplest way to check this would be the following code
$containsValues = !array_diff($arrIntRequestPropertyIds, $arrIntPropertyIds);
Would return true or false

<?php
$arrIntPropertyIds = [ 1,2,3,4,5,6,7,8,9,10];
$arrIntRequestPropertyIds = [ 3, 5, 7];
$intersect = count(array_intersect($arrIntPropertyIds, $arrIntRequestPropertyIds));
if ($intersect == count($arrIntRequestPropertyIds)) {
echo '$arrIntPropertyIds include all of $arrIntRequestPropertyIds';
} elseif ($intersect > 0) {
echo '$arrIntPropertyIds include part of $arrIntRequestPropertyIds';
} else {
echo '$arrIntPropertyIds not include any of $arrIntRequestPropertyIds';
}
run PHP online

Related

Problem during creating Pyramid Star Patterns in PHP [duplicate]

This question already has answers here:
PHP Displaying a number of asterisks depending on the number given in the input field
(4 answers)
Closed 11 months ago.
Question :
My Code :
<html\>
Enter the number of rows:
<?php
if($_POST)
{
$row = $_POST['row'];
if(!is_numeric($row))
{
echo "Make sure you enter a NUMBER";
return;
}
else
{
for($row=0;$row<=1;$row++){
for($j=0;$j<=$row;$j++){ echo "#"; } echo ""; }}}?>
The problem is it's showing only two rows
I expected as shown in the photo
$row = 10;
for($i=0;$i<=$row;$i++){
for($j=0;$j<=$i;$j++){ echo "#"; } echo "<br>"; }
You are overriding the $row variable.
Also, you don't need the else since you are returning in case the if(!is_numeric) is true;
This should do it.
if(isset($_POST['row'])) {
$rows = $_POST['row'];
if(!is_numeric($rows))
{
echo "Make sure you enter a NUMBER";
return;
}
for($row=0;$row<=$rows;$row++){
for($j=0;$j<=$row;$j++){
echo "#";
}
echo "\n";
}
}
You can make use of the PHP function str_repeat to simplify the script.
This would only take 1 loop, so you don't get confused with the variable names.
$row = 10;
$i = 1;
while ($i <= $row)
{
echo str_repeat("#", $i); echo "\n";
$i ++;
}
Working Example here.

Filled array detected as true [duplicate]

This question already has answers here:
PHP "If true" test on array always returns true?
(1 answer)
Is an array considered as boolean true in php?
(6 answers)
Closed 2 years ago.
I receive an array from a method, and I check the value of it. If the array equals to true, it should do something, but if not, it has to do something else. Here's my if statement :
$existence_status = $model->getReportExistenceStatus($validFormData['start_date'], $validFormData['end_date'], $validFormData['start_hour'] . ":00", $validFormData['end_hour'] . ":00");
var_dump($existence_status);
if ($existence_status) {
// Report was not found, continue processing a complete API request
// Get the report from the model
$report_data = $model->getReport($validFormData['start_date'], $validFormData['end_date'], $validFormData['start_hour'], $validFormData['end_hour'], $access_token);
// Set the data on the chart
if ($report_data !== false) {
$chart_status = true;
$start_date = $validFormData['start_date'];
$end_date = $validFormData['end_date'];
$start_hour = $validFormData['start_hour'];
$end_hour = $validFormData['end_hour'];
$success = $report_data['success'];
$failed = $report_data['failed'];
} else {
$chart_status = false;
}
} else {
// Report was found, get the data and print them
$chart_status = true;
$start_date = $validFormData['start_date'];
$end_date = $validFormData['end_date'];
$start_hour = $validFormData['start_hour'];
$end_hour = $validFormData['end_hour'];
$success = $existence_status['success'];
$failed = $existence_status['failed'];
}
I just found out that if the returned value from the call of the getReportExistenceStatus is an array, it will go in the if instead of the else.
Here is the value of the $existence_status (got it from the var_dump) :
array (size=2)
'success' => int 100
'failed' => int 0
But it still goes in the if statement instead of the else.
I've found a way to get around that problem (I'm using php !is_array($existance_status) as condition), but that really perturbate me, because, afaik, an filled array is not considered as "true", no ?
Is that normal ?

PHP Json object property/value error handling

{
"AFL Round 16":{
"4166082":{
"EventID":4166082,
"ParentEventID":3744759,
"MainEvent":"North Melbourne v Hawthorn",
"OutcomeDateTime":"2014-07-06 02:00:00",
"Competitors":{
"Competitors":[
{
"Team":"Hawthorn To Win 40+",
"Win":"3.00"
}
],
"ActiveCompetitors":1,
"TotalCompetitors":1,
"HasWinOdds":true
},
"EventStatus":"Open"
},
"4167064":{
"EventID":4167064,
"ParentEventID":3744759,
"MainEvent":"North Melbourne v Hawthorn",
"OutcomeDateTime":"2014-07-06 02:00:00",
"Competitors":{
"Competitors":[
{
"Team":"Hawthorn (-5.5)",
"Win":"1.86"
},
{
"Team":"North Melbourne (+5.5)",
"Win":"1.86"
}
],
"ActiveCompetitors":2,
"TotalCompetitors":2,
"HasWinOdds":true
},
"EventStatus":"Open"
}
}
}
I am parsing json objects using PHP and here is a sample of my json. Everything is working fine. I just want to check if object property/value exists if yes then throw errors for example i want to check EventID, ParentEventID, OutcomeDateTime, Team (inside Competitors array) are valid property name and they are not null.
This is few lines of my code.
$SortedByDate = array();//Sorted By Date Array i.e key=EventID and value=OutcomeDateTime
//Accessing Root Element0
foreach ($json_a as $root_element => $childnode) {
//Accessing child elements
foreach( $childnode as $cKey => $subChild) {
$OutcomeDateTime_UTC=gmdate('Y-m-d H:i:s', strtotime($subChild['OutcomeDateTime']));
//checking ParentEventID=0 , Competitors array = 2 and OutcomeDateTime is greater than current time + 10 min
if($subChild['ParentEventID']=='0' and is_array($subChild['Competitors']['Competitors']) and count ($subChild['Competitors']['Competitors']) == 2 and $OutcomeDateTime_UTC>=$NewDateTime and !preg_match('/\(Live\)/',$subChild['MainEvent']) ) {
//Inserting values into array
$SortedByDate[$cKey] = $subChild['OutcomeDateTime'];;
}
}
}
I tired to add if(isset($subChild['OutcomeDateTime']) || is_null($subChild['OutcomeDateTime'])) to check if property name is OutcomeDateTime and it is not null and change json proerty's value (OutcomeDateTime) to null but i get an error that "Invalid argument supplied for foreach()"
is there a better way to check property/values before parsing???
Try this and see if it does what you mean. If not, I don't understand. If it does solve your problem I'll explain why...
//Accessing Root Element0
foreach ($json_a as $root_element => &$childnode) {
//Accessing child elements
foreach( $childnode as $cKey => &$subChild) {
$OutcomeDateTime_UTC=gmdate('Y-m-d H:i:s', strtotime($subChild['OutcomeDateTime']));
//checking ParentEventID=0 , Competitors array = 2 and OutcomeDateTime is greater than current time + 10 min
if($subChild['ParentEventID']=='0' && is_array($subChild['Competitors']['Competitors']) && count ($subChild['Competitors']['Competitors']) == 2 && $OutcomeDateTime_UTC>=$NewDateTime && !preg_match('/\(Live\)/',$subChild['MainEvent']) ) {
//Inserting values into array
$SortedByDate[$cKey] = $subChild['OutcomeDateTime'];
}
if(isset($subChild['OutcomeDateTime']) && !is_null($subChild['OutcomeDateTime'])) {
$subChild['OutcomeDateTime'] = null;
}
}
}
I just want to check if object property/value exists if yes then throw errors
Your wording doesn't make sense and little bit odd, maybe you were saying that you want to validate each key (if they exist) and if each value of those keys are not null
for example i want to check EventID, ParentEventID, OutcomeDateTime, Team (inside Competitors array) are valid property name and they are not null.
Here is a fiddle. Try to remove some elements inside the json string to check: Fiddle
$json_a = '{ "AFL Round 16":{ "4166082":{ "EventID":4166082, "ParentEventID":3744759, "MainEvent":"North Melbourne v Hawthorn", "OutcomeDateTime":"2014-07-06 02:00:00", "Competitors":{ "Competitors":[ { "Team":"Hawthorn To Win 40+", "Win":"3.00" } ], "ActiveCompetitors":1, "TotalCompetitors":1, "HasWinOdds":true }, "EventStatus":"Open" }, "4167064":{ "EventID":4167064, "ParentEventID":3744759, "MainEvent":"North Melbourne v Hawthorn", "OutcomeDateTime":"2014-07-06 02:00:00", "Competitors":{ "Competitors":[ { "Team":"Hawthorn (-5.5)", "Win":"1.86" }, { "Team":"North Melbourne (+5.5)", "Win":"1.86" } ], "ActiveCompetitors":2, "TotalCompetitors":2, "HasWinOdds":true }, "EventStatus":"Open" } }}';
$json_a = json_decode($json_a, true);
$json_a = reset($json_a); // ignore these parts since you already know how to get them
$errors = array();
$valid_keys = array('EventID', 'ParentEventID', 'OutcomeDateTime', 'MainEvent', 'Competitors', 'EventStatus');
foreach($json_a as $event_id => $values) {
// check for keys
$keys = array_keys($values);
foreach($valid_keys as $key) {
if(!in_array($key, $keys)) {
// check keys, not valid if it goes here
$errors[] = "<b>$key</b> is missing on your data <br/>";
} else {
// valid keys, check values
if(empty($values[$key])) {
// empty values
$errors[] = "<b>$key</b> has an empty value <br/>";
}
}
}
// next checking, competitors
foreach($values['Competitors']['Competitors'] as $competitors) {
if(empty($competitors)) {
// if competitors is empty
$errors[] = "<b>Competitors</b> has an empty value <br/>";
}
}
}
if(!empty($errors)) {
// not a good error triggering device, just change this to something else
trigger_error('<pre>'.implode($errors).'</pre>', E_USER_ERROR);
}

How to check a variable value is in an array? [duplicate]

This question already has answers here:
How can I check if an array contains a specific value in php? [duplicate]
(8 answers)
Closed 9 years ago.
How to check php variable with array?
When $user_check = "ccc";
<?php
$user_group = array('aaa' , 'bbb' , 'ccc' , 'ddd');
$name_group = join("','",$user_group);
if ($name_group != $user_check) {
echo "not found."
} else {
echo "found."
}
?>
Try in_array()
if (in_array($user_check,$user_group))
{ echo "found."; }
else
{ echo "Not found."; }
Check the documentation on this link.
Use in_array Function
if ( in_array($user_check, $user_group) ) {
echo "found."
} else {
echo "not found."
}

Check if field exists in for function PHP [duplicate]

This question already has answers here:
How can I check if an array element exists?
(8 answers)
Closed 8 years ago.
I have this PHP script:
for ($desc=1; $_POST['ddata'.$desc]; $desc++) {
if($_POST['ddata'.$desc]){
if ($desc == 1){
$ddata = $_POST['ddata'.$desc];
$dlocatie = $_POST['dlocatie'.$desc];
} else {
$ddata = $ddata.' / '.$_POST['ddata'.$desc];
$dlocatie = $dlocatie.' / '.$_POST['dlocatie'.$desc];
}
}
}
If I have 5 ddata fields, it gives this error: Undefined index: ddata6
How can I check if that fields exists so I can prevent this error?
How can I check if that fields exists so I can prevent this error?
use isset() to check if item exists prior accessing it.
Instead of if($_POST['ddata'.$desc]), you can do:
if(isset($_POST['ddata'.$desc]))
Or:
if(array_key_exists('ddata'.$desc, $_POST))
You can go for
if(isset($_POST['thekey']))
or more traditionally:
if(array_key_exists('thekey', $_POST))
Try
isset($_POST['ddata'.$desc])
Thanks
Check for what fields exist BEFORE you do your loop, by using preg_grep to scan the array for your ddata... fields.
$ddata_fields = preg_grep('/^ddata\d+$/', array_keys($_POST));
foreach($ddata_fields as $field) {
$ddata = $_POST[$field];
etc...
}
Just add a if(isset($_POST['ddata'.$desc])){} instead of if($_POST['ddata'.$desc]){}
Change the section beginning with...
if($_POST['ddata'.$desc]){
To....
for ($desc=1; $_POST['ddata'.$desc]; $desc++) {
if (isset($_POST['ddata'.$desc])) {
$ddata = $_POST['ddata'.$desc'];
} else {
continue;
}
switch($desc) {
case "1" :
$ddata = $_POST['ddata'.$desc];
$dlocatie = $_POST['dlocatie'.$desc];
break;
case "2" :
case "3" :
case "4" :
case "5" :
$ddata = $ddata.' / '.$_POST['ddata'.$desc];
$dlocatie = $dlocatie.' / '.$_POST['dlocatie'.$desc];
break;
}
}

Categories