How to check if an array is empty in PHP(Codeigniter) - php

Here it's my sample of code :
public function show($imei,$start_time,$end_time,$dateto) {
$from_time = str_replace('-','/',$start_time);
$fromi=strtotime($from_time . ' ' . $end_time);
$too1=strtotime($from_time . ' ' . $dateto);
$data['coordinates'] = $this->road_model->get_coordinatesudhetime($imei, $fromi, $too1);
$this->load->view('road/show', $data);
if (!empty($data))
{
echo 'Array it's empty*';
}
}
I want to check when $data it's empty .

if (empty($data))
{
echo "array is empty";
}
else
{
echo "not empty";
}
or count($data) returns the size of array.

You can do this way also
if(is_array($data) && count($data)>0)
{
echo "not empty";
}else{
echo "empty";
}

Related

first loop through everything, than if 1 is true do something

So I have this foreach loop that checks if $testsubject is equal to the results from the array.
But I want it to check all the results first and if one is true than go further and check the date and else just echo that the voucher is not corect.
the purpose of the code is that the user puts in a voucher code which for now is $testsubject than I check if the voucher exists in the system if that is true I check if it is not expired with the date function and then I cut the discount for the price $testamount.
image of the echo's https://imagebin.ca/v/3xQuiAClVsAG
index.php
function display()
{
$arrContextOptions = [
"ssl" => [
"verify_peer" => false,
"verify_peer_name" => false,
],
];
$getVoucherList = "https://www.planyo.com/rest/?method=list_vouchers&api_key=yourkey&resource_id=110556";
$cleanVoucherList = preg_replace("/ /", "%20", $getVoucherList);
$voucherlist = file_get_contents("$cleanVoucherList", false, stream_context_create($arrContextOptions));
$voucherList = json_decode($voucherlist, true);
$testsubject = "TESTVOUCHER";
$testamount = "5,00";
foreach ($voucherList['data']['results'] as $testVoucher => $testVoucherArr) {
if ($testsubject == $testVoucherArr['code']) {
echo $testsubject . " is not equal to " . $testVoucherArr['code'] . "<br>";
echo $testVoucherArr['rental_end_date'] . "<br>";
echo $testVoucherArr['discount_value'] . "<br>";
if (date("Y-m-d") <= $testVoucherArr['rental_end_date']) {
echo "this code can be used <br>";
echo $testamount - $testVoucherArr['discount_value'] . "<br>";
} else {
echo "this code cannot be used";
}
;
} else {
echo $testsubject . " is not equal to " .
$testVoucherArr['code'] . "<br>";
}
}
}
if (isset($_POST['submit'])) {
display();
}
Would this work for you? If the code is valid, then you enter a function which checks the date. After the function has ended, the foreach loop will end by using "break;"
function testVoucherDate($voucher)
{
if (date("Y-m-d") <= $testVoucherArr['rental_end_date']) {
echo "this code can be used <br>";
echo $testamount - $testVoucherArr['discount_value'] . "<br>";
} else {
echo "this code cannot be used";
};
}
foreach ($voucherList['data']['results'] as $testVoucher => $testVoucherArr) {
if ($testsubject == $testVoucherArr['code']) {
echo $testsubject . " is not equal to " . $testVoucherArr['code'] . "<br>";
echo $testVoucherArr['rental_end_date'] . "<br>";
echo $testVoucherArr['discount_value'] . "<br>";
testVoucherDate($testVoucherArr);
break;
} else {
echo $testsubject . " is not equal to " .
$testVoucherArr['code'] . "<br>";
}
}
EDIT: I've put the function above the loop, so no errors of undefined functions will occur
First set a flag to true, then loop setting the flag to false if there is an error. Then test the flag:
$flag = true; // SET A FLAG
foreach($a as $b){
if($b !== 'Hello')$flag = false; // IF contidtion not met, set flag to true
}
if($flag === false){ // TEST IF flag result
echo 'Dear oh dear';die;
}
foreach(....){ // GO ON if flag === true
....
}

Show only ones that do not match PHP

I'm trying to use a multiple foreach and if statements to give me a list of list of people that have not been matched. I have the below code, I am able to get this to successfully give me a list of people it does match.
What I want to do is it echo each the ID from the $tenant_id foreach that have not been found in the $value2 foreach, am I doing something wrong? It will only output nothing?
foreach($array_93 as $value) {
$tenant_id = $value['id'];
$limit = 0;
foreach($obj->response->entries as $value2) {
if($limit==1) break;
if ($value2->{100} == 'true' && $value2->{114} == $tenant_id)
{echo $value['id']; // This should echo ID's that have not been found.}
$limit++;
}
}
};
UPDATE >>
After continuing to try and get this working I have got to this point, I am able to to use this to show which ID's are all 'n' as per screenshot after. The first one is all n's so this has not matched, how can I now make just the ones with all n's ID show?
foreach($array_93 as $value) {
echo '<b>'.$value['id'].'</b>';
echo '<br />';
foreach($obj->response->entries as $value2) {
if (strpos($value2->{114}, $value['id']) === false)
{
echo '<i>n</i>';
} else {
echo '<b>Y</b>';
}
}
echo '<br />';
};
Use a flag with Y-found state:
foreach($array_93 as $value) {
$Yfound = false;
foreach($obj->response->entries as $value2) {
if (strpos($value2->{114}, $value['id']) !== false) {
$Yfound = true;
}
}
if(!$Yfound) {
echo $value['id'] . ' has n`s only<br>';
}
}
Hi you should not echo right away :
foreach($array_93 as $value) {
//echo '<b>'.$value['id'].'</b>';
//echo '<br />';
//don't print yet
$output = ""; //this to store your n and Y strings.
$n = 0; //Here you store the number of times Y appears
foreach($obj->response->entries as $value2) {
if (strpos($value2->{114}, $value['id']) === false)
{
$output .= '<i>n</i>';//concatenating
} else {
$output .= '<b>Y</b>';
$n++;
}
}
//then test if there is a y and echo output.
if($n == 0){
echo '<b>'.$value['id'].'</b>';
echo '<br />';
echo $output;
echo '<br />';
}
};

Improving if statements in sql query

I've written some code that works fine, but is extremely verbose and would like a pointer on how to make it more efficient. I'm running different SQL queries because a single one returns too many results;
$sql1 = "select blah blah blah";
$sql2 = "select blah blah blah";
$sql3 = "select blah blah blah";
$response1 = $client->executeSQLQuery(array("sql"=>$sql1));
$response2 = $client->executeSQLQuery(array("sql"=>$sql2));
$response3 = $client->executeSQLQuery(array("sql"=>$sql3));
if( is_array($response1->return->row) )
{
foreach($response1->return->row as $numbers)
{
echo $numbers->dnorpattern . "<br>";
$count++;
}
}
else
{
echo $response1->return->row->dnorpattern . "<br>";
$count++;
}
if( is_array($response2->return->row) )
{
foreach($response2->return->row as $numbers)
{
echo $numbers->dnorpattern . "<br>";
$count++;
}
}
else
{
echo $response2->return->row->dnorpattern . "<br>";
$count++;
}
if( is_array($response3->return->row) )
{
foreach($response3->return->row as $numbers)
{
echo $numbers->dnorpattern . "<br>";
$count++;
}
}
else
{
echo $response3->return->row->dnorpattern . "<br>";
$count++;
}
So, I would like to change the if statements to be a single if statement like this;
if( is_array($response1->return->row) )
{
foreach($response1->return->row as $numbers)
{
echo $numbers->dnorpattern . "<br>";
$count++;
}
}
else
{
echo $response1->return->row->dnorpattern . "<br>";
$count++;
}
The integer for $sql and $response is predictable, so I should be able to use a for statement
for($x=1, $x<=3, $x++)
{
if( is_array($response[$x]->return->row) )
{
foreach($response[$x]->return->row as $numbers)
{
echo $numbers->dnorpattern . "<br>";
$count++;
}
}
else
{
echo $response[$x]->return->row->dnorpattern . "<br>";
$count++;
}
}
But this does not work, can someone explain how I can increment the integer properly?
You can use curly braces syntax:
for($x=1; $x<=3; $x++)
{
if( is_array(${'response' .$x}->return->row) )
{
foreach(${'response' .$x}->return->row as $numbers)
{
echo $numbers->dnorpattern . "<br>";
$count++;
}
}
else
{
echo ${'response' .$x}->return->row->dnorpattern . "<br>";
$count++;
}
}
OR save your three response objects in an array, and use your original syntax:
$response = [];
$response[1] = $client->executeSQLQuery(array("sql"=>$sql1));
$response[2] = $client->executeSQLQuery(array("sql"=>$sql2));
$response[3] = $client->executeSQLQuery(array("sql"=>$sql3));
Though you could probably just write a better SQL query and vastly simplify things

php: echo an error message

code :
$searchText = '3423, 2453, 3245 , 2425, 6765';
$numbers = str_replace(", ", ",", $searchText);
$code = explode(",", $numbers);
if ( (preg_match("/[^0-9]/i"), $code) || (strlen($code) != 4) ) {
$searchingError= 'Can not cantain string and more than 4 digists number!';
echo '<script type="text/javascript">';
echo "alert('" . $searchingError . "')";
echo "</script>";
}
function validate ($a) {
if (ctype_digit($a) && (strlen($a) == 4)) {
return "'$a'" ;
} else {
//$searchingError= 'Can not cantain string and more than 4 digists number!';
//echo '<script type="text/javascript">';
//echo "alert('" . $searchingError . "')";
//echo "</script>";
}
}
$parsed = array_map( "validate",$code);
print_r($parsed);
$code = '(' . preg_replace('/\,+/', ',',implode(',', $parsed)) . ')';
echo '<br />' . $code;
In this code, is there a way to identify $searchText have only 4 digits numbers or it contain string etc. If it's so, I want to echo an error message.
Thanks for any comments.
Check if $code is a text using is_int and the length of each number using strlen();
in an if statement:
if (is_int($code)) {
if (strlen($num1) = 4 && strlen($num2) ...) {
//code here
}
else
echo "Error.";
}
else
echo "The search is text";
This will work to verify that they are digits only and 4 characters only...
//is not digits or //is not 4 characters in length
if ( (preg_match("/[^0-9]/i"), $code) || (strlen($code) != 4) ) {alert error...}
GOT IT!
<?php
$a = "4444 , 111X , 565656, 4444";
$a = str_replace(" ", "", $a);
$b = explode(",",$a);
function validate($v){
if ((strlen($v)!=4)||(preg_match("/[^0-9]/i", $v))) { echo 'error<br/>'; }else{ echo 'success<br/>'; };
}
array_filter($b,"validate");
echo 'complete';
?>

If statement with 2 conditions

I was practising statements and ran into a problem. I'm trying to make it so that if $child3 is available, then it will echo all three children, like how when $child2 is available, it echos Kim & Pom. What did I do wrong?
$child = "Kim";
$child2 = "Pom";
$child3 = "Rob";
if($child2) {
echo $child; echo " "; echo $child2;
} elseif($child3) {
echo $child; echo " "; echo $child2; echo " "; echo $child3;
} else {
echo $child;
}
Try reversing the conditions:
$child = "Kim";
$child2 = "Pom";
$child3 = "Rob";
if($child3){
echo $child . " " . $child2 . " " . $child3;
}else if($child2){
echo $child . " " . $child2;
}else{
echo $child;
}
You might also like the wonderful string concatenation operator ..
elseif only executes if none of the preceding ifs or elseifs executed. So you'll want to move it above the other if:
if($child3) {
echo $child; echo " "; echo $child2; echo " "; echo $child3;
} elseif($child2) {
echo $child; echo " "; echo $child2;
} else {
echo $child;
}
Probably you want something like this:
$child = 1; // Or $child = 2; Or $child = 3;
if ($child == 1) {
echo 'Kim';
} elseif ($child == 2) {
echo 'Pom';
} else {
echo 'Rob';
}
But I recommend switch() as soon as you have elseif.
$child = "Kim";
$child2 = "Pom";
$child3 = "Rob";
if($child3){
echo $child; echo " "; echo $child2; echo " "; echo $child3;
}elseif($child2){
echo $child; echo " "; echo $child2;
}else{
echo $child;
}
How about this?
if ($child) {
echo "{$child} ";
}
if ($child2) {
echo "{$child2} ";
}
if ($child3) {
echo "{$child3} ";
}
If that's your actual code, you'll only ever get Kim Rob, as $child2 will always be true, thereby bypassing your else clauses.
Also, you can combine your echos into:
echo "$child $child2 $child3";
It makes it far easier to read that way.
Here's how I would do it. I agree with Dragon that a switch would be clearer/better.
switch (true)
{
case (isset($child,$child2,$child3)) :
echo $child . ' ' . $child2 . ' ' . $child3;
break;
case (isset($child, $child2)) :
echo $child . ' ' . $child2;
break;
case (isset($child)) :
echo $child;
break;
}

Categories