php: echo an error message - php

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';
?>

Related

How to count/sum this values of the same word in PHP?

I am confused to count these words,
I've some data like this :
web = 1
sistem=1
web=1
sistem=1
web=1
sistem=1
sistem=0
sistem=0
web=0
sistem=0
web=0
sistem=0
web=0
web=0
I want to make result like this :
web = 3
sistem = 3
I'm using array_count_values(), but this result is not good
Array ( [web=1] => 3 [sistem=1] => 3 [sistem=0] => 4 [web=0] => 4 )
My code like this :
foreach ($g as $key => $kata) {
if (strpos($cleanAbstrak, $kata)) {
echo $kata . $ada . "<br>";
$p[] = $kata . "=" . $ada;
// print_r($p);
echo "<br><br>";
} else {
echo $kata, $tidak . "<br>";
$q[] = $kata . "=" . $tidak;
// $m = explode(" ", $q);
// print_r($q);
// echo $q . '<br>';
echo "<br><br>";
}
}
$s = array_merge($p, $q);
echo "<br><br>";
print_r($s);
echo "<br>";
$f = array_count_values($s);
// print_r($f);
echo "<br><br>";
thank you very much if you are willing to help me
RESULT THIS CODE
Another simple way is use a counter like that:
$web=0;
$sistem=0;
foreach ($g as $key => $kata) {
if (strpos($cleanAbstrak, $kata)) {
$sistem=$sistem + $ada;
} else {
$web=$web+$tidak
}
}
echo 'web='.$web.'<br> sistem='.$sistem;
First, you need to separate word and value.
Second, you need to check the value : if it's zero you let it go (can't hold it back anymore). Else you count the value ; if it's written, i suppose it can be greater than 1 ; if it's not, it should be "word", or nothing (which would greatly facilitate counting).
Something like
<?php
$tab = [
'web=1',
'sistem=1',
'web=1',
'sistem=1',
'web=1',
'sistem=1',
'sistem=0',
'sistem=0',
'web=0',
'sistem=0',
'web=0',
'sistem=0',
'web=0',
'web=0',
];
$tab_clean = [];
foreach($tab as $item) {
preg_match('/([a-z]+)=([\d]+)/', $item, $matches);
//print_r($matches);
$word = $matches[1];
$number = $matches[2];
for($i = 0; $i < $number; $i++) {
$tab_clean[] = $word;
}
}
$tab_count = array_count_values($tab_clean);
print_r($tab_count);
?>

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
....
}

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

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";
}

Echo all values in php array as a sentence

Is it possible to display an array as a sentence? So between each of the values there would be ", " except before the last value there would be " and ".
I have taken this little piece of code to use within an example:
<?php
$cars=array("Volvo","BMW","Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>
This works great for three values but I need it to work for between 1 and 15 values.
Thanks
$carsCount = count($cars);
if ($carsCount == 1) {
$sentence = $cars[0] . '.';
} else {
$partial = array_slice($cars, 0, $carsCount-1);
$sentence = implode(', ', $partial) . ' and ' . $cars[$carsCount-1];
}
echo $sentence;
$array = array("Volvo", "BMW", "Toyota");
$sentence = '';
foreach($array as $k => $v) {
if (count($array) == 1) {
$sentence = $v;
break;
}
else if ($k == count($array)-1) {
$sentence .= 'and ' . $v;
}
else {
$sentence .= $v . ', ';
}
}
echo $sentence;
Above returns the following: Volvo, BMW, and Toyota
There is another way [shorter], [faster].
$cars = array("Volvo", "BMW", "Toyota", "Fiat");
if (count($cars) > 1) {
$lastVal = array_pop($cars);
echo implode(",", $cars)." and ".$lastVal;
} else {
echo $cars[0];
}

PHP Search CSV file. Search filter minimum characters

I'm noob at PHP. I have PHP script to search CSV file.
How can I add search filter minimum x characters else it shows error message?
<?php
if ( !empty ( $_GET['search'] ) ) {
$search = mb_strtolower($_GET['search']);
$lines = file('file.csv');
$found = false;
foreach($lines as $line)
{
$line = mb_strtolower($line);
if(strpos($line, $search) !== false)
{
$line = explode(',', $line);
$found = true;
$str = $line[0];
$str = strtoupper($str);
echo "<div class='datagrid'><table><thead><tr><th>MODEL</th><th width='50px;'>QUANTITY</th><th width='155px;'>MAIL</th></tr></thead><tbody><tr>";
echo "<td style='font-weight:bold;'>" . $str; echo "</td>";
echo "<td>" . $line[1]; echo "</td>";
echo "<td><a href='mailto:mailaddress?subject=$str' id='button'>Send</a></td>";
echo "</tr>";
echo "</tbody></table></div>";
}
}
if(!$found) {
echo 'Nothing found.';
}
}
?>
You can use the strlen function to know how many characters search term has
http://php.net/manual/en/function.strlen.php
<?php
$search_min_len = 3;//Change this to your needs
if ( !empty ( $_GET['search'] ) ) {
$search = mb_strtolower($_GET['search']);
if(strlen($search ) >= $search_min_len)
{
$lines = file('file.csv');
$found = false;
foreach($lines as $line)
{
$line = mb_strtolower($line);
if(strpos($line, $search) !== false)
{
$line = explode(',', $line);
$found = true;
$str = $line[0];
$str = strtoupper($str);
echo "<div class='datagrid'><table><thead><tr><th>MODEL</th><th width='50px;'>QUANTITY</th><th width='155px;'>MAIL</th></tr></thead><tbody><tr>";
echo "<td style='font-weight:bold;'>" . $str; echo "</td>";
echo "<td>" . $line[1]; echo "</td>";
echo "<td><a href='mailto:mailaddress?subject=$str' id='button'>Send</a></td>";
echo "</tr>";
echo "</tbody></table></div>";
}
}
if(!$found) {
echo 'Nothing found.';
}
}
else
{
echo 'Minimum '.$search_min_len.' characters error';
}
}
?>
Hope it helps

Categories