Echo once in a foreach - php

I have a code in PHP. However when I echo, nothing is printed on page.
Can anyone help me?
public function checkcharacter(Request $request)
{
$woord = str_split($request->session()->get('woord'));
foreach ($woord as $letter) {
if ($request->letter === $letter) {
// return view('hangman')->getData (['goed', 'goed gedaan' =>$woord]); // =>$dottedword
return view('hangman')->with (['woord' => $woord, 'correct' => 'fout']);
}
else {
echo "wrong answer!";
}
}
}

If I understand you correctly and you want to get only wrong answer! string once in the case if the latter isn't the same you need to use break; construction.
public function checkcharacter(Request $request)
{
$woord = str_split($request->session()->get('woord'));
foreach ($woord as $letter) {
if ($request->letter !== $letter) {
echo "wrong answer!";
break;
}
// return view('hangman')->getData (['goed', 'goed gedaan' =>$woord]); // =>$dottedword
return view('hangman')->with(['woord' => $woord, 'correct' => 'fout']);
}
}
Hope I understand your question in the proper way.
Upd 1.0
If you don't want to break the loop, then I have the second way of resolving your problem:
public function checkcharacter(Request $request)
{
$woord = str_split($request->session()->get('woord'));
$isCorrect = true;
foreach ($woord as $letter) {
if ($request->letter !== $letter) {
$isCorrect = false;
}
// return view('hangman')->getData (['goed', 'goed gedaan' =>$woord]); // =>$dottedword
return view('hangman')->with(['woord' => $woord, 'correct' => 'fout']);
}
if (!$isCorrect) {
echo 'wrong answer!';
}
}

If you just want to check if the letter is in the word, there is no need for a loop, just check if the letter is in the word - I use strpos()
public function checkcharacter(Request $request)
{
if ( strpos ($request->letter, $request->session()->get('woord')) !== false) {
return view('hangman')->with (['woord' => $woord, 'correct' => 'fout']);
}
else {
return view('hangman')->with (['woord' => $woord, 'correct' => 'false']);
}
}
Note that both branches return a view - the second one where the letter isn't found sets 'correct' => 'false' which you may need to change to suit your needs.

The following else block should be outside of foreach block
else {
echo "wrong answer!";
}
So suppose the if condition is success then the flow will return without any echo. I have not run this snippet. Please check it at your end.
public function checkcharacter(Request $request)
{
$woord = str_split($request->session()->get('woord'));
foreach ($woord as $letter) {
if ($request->letter === $letter) {
// return view('hangman')->getData (['goed', 'goed gedaan' =>$woord]); // =>$dottedword
return view('hangman')->with (['woord' => $woord, 'correct' => 'fout']);
}
}
// if answer is not found then will give the following echo once.
echo "wrong answer!";
}

Related

Array to string conversion in class.settings.php at 833 during PHP 7.4 Code Upgrade

I had zero knowledge of php until I was told by my hosting company that I had to update my websites code to be compatible with php 7.4 and mysqli.I am quite proud of myself in that I managed to fix at least 300 errors before having to reach out for help to another coder. But with his busy schedule I hate bothering him when I get stuck. He barely is able to make a little time one day a week. I believe I have finally came to the light at the end of the tunnel. I am encountering two errors left as of now. These two have me so confused. I have googled trying to find answers but can't comprehend exactly what to do since I don't understand the php language. I am hoping someone here would be so kind as to help me. I would love to find a person that has skype that loves teaching new people and can help me if I come across something else. I hate flooding this community if I run into a error here and there. I just hope that after fixing these final 2 no more appear. It seemed like I would fix one and ten more would come about. Im thinking this has to come to an end sooner or later.
The code has the line number next to the error.
ERROR #1:
Array to string conversion in class.settings.php at 833
private function ManageReturnsSettings($messages=array())
{
$GLOBALS['Message'] = GetFlashMessageBoxes();
foreach ($this->all_vars as $var) {
if (is_string(GetConfig($var)) || is_numeric(GetConfig($var))) {
$GLOBALS[$var] = isc_html_escape(GetConfig($var));
} elseif (is_array(GetConfig($var))) {
LINE 833> $GLOBALS[$var.'Area'] = isc_html_escape(implode("\r\n", GetConfig($var)));
}
}
// Are returns enabled?
if (GetConfig('EnableReturns')) {
$GLOBALS['IsEnableReturns'] = "checked=\"checked\"";
}
// Can store credits be issued?
if (GetConfig('ReturnCredits')) {
$GLOBALS['IsReturnCredits'] = "checked=\"checked\"";
}
if (GetConfig('EmailOwnerOnReturn')) {
$GLOBALS['IsReturnNotifyOwner'] = "checked=\"checked\"";
}
if (GetConfig('SendReturnConfirmation')) {
$GLOBALS['IsReturnNotifyCustomer'] = "checked=\"checked\"";
}
if (GetConfig('NotifyOnReturnStatusChange')) {
$GLOBALS['IsReturnNotifyStatusChange'] = "checked=\"checked\"";
}
$this->template->display('settings.returns.manage.tpl');
}
Error #2:
count(): Parameter must be an array or an object that implements Countable in Core.php at 391
// add multibyte extensions if possible
if (function_exists('mb_get_info')) {
function twig_length_filter(Twig_Environment $env, $thing)
{
return is_string($thing) ? mb_strlen($thing, $env->getCharset()) : count($thing);
}
function twig_upper_filter(Twig_Environment $env, $string)
{
if (null !== ($charset = $env->getCharset())) {
LINE 391> return mb_strtoupper($string, $charset);
}
return strtoupper($string);
}
function twig_lower_filter(Twig_Environment $env, $string)
{
if (null !== ($charset = $env->getCharset())) {
return mb_strtolower($string, $charset);
}
return strtolower($string);
}
function twig_title_string_filter(Twig_Environment $env, $string)
{
if (null !== ($charset = $env->getCharset())) {
return mb_convert_case($string, MB_CASE_TITLE, $charset);
}
return ucwords(strtolower($string));
}
function twig_capitalize_string_filter(Twig_Environment $env, $string)
{
if (null !== ($charset = $env->getCharset())) {
return mb_strtoupper(mb_substr($string, 0, 1, $charset)).
mb_strtolower(mb_substr($string, 1, mb_strlen($string), $charset), $charset);
}
return ucfirst(strtolower($string));
}
}
// and byte fallback
else
{
function twig_length_filter(Twig_Environment $env, $thing)
{
return is_string($thing) ? strlen($thing) : count($thing);
}
function twig_title_string_filter(Twig_Environment $env, $string)
{
return ucwords(strtolower($string));
}
function twig_capitalize_string_filter(Twig_Environment $env, $string)
{
return ucfirst(strtolower($string));
}
}
function twig_ensure_traversable($seq)
{
if (is_array($seq) || (is_object($seq) && $seq instanceof Traversable)) {
return $seq;
} else {
return array();
}
}
function twig_test_sameas($value, $test)
{
return $value === $test;
}
function twig_test_none($value)
{
return null === $value;
}
function twig_test_divisibleby($value, $num)
{
return 0 == $value % $num;
}
function twig_test_even($value)
{
return $value % 2 == 0;
}
function twig_test_odd($value)
{
return $value % 2 == 1;
}
function twig_test_constant($value, $constant)
{
return constant($constant) === $value;
}
function twig_test_defined($name, $context)
{
return array_key_exists($name, $context);
}
function twig_test_empty($value)
{
return null === $value || false === $value || '' === (string) $value;
}

rewrite using array filter

How would I write the following foreach with some conditions using array_filter?
foreach ($categories as $category) {
if ($this->request->getParam('category_id')) {
if ($category->getCategoryId() == $this->request->getParam('category_id')) {
$selectedCategory = $category;
break;
}
} else {
No category id in request. Select the first one.
if (array_key_exists(0, $categoryTree) &&
$category->getCategoryId() == $categoryTree[0]['id']
) {
$selectedCategory = $category;
break;
}
}
}
First off, using array_filter isn't helpful in this case as it reduces an array instead of selecting an element. But to show its principles, you could rewrite the code to something like this.
if($this->request->getParam('category_id')){
$filteredCategories = array_filter($categories, function ($category) use ($this){
return $category->getCategoryId() == $this->request->getParam('category_id');
});
if(count($filteredCategories)>0){
return $filteredCategories[0];
}
} else {
[...]
}
I think you want an intersection function and not an array filter.
function key_compare_func($key1, $key2)
{
if ($key1 == $key2->getCategoryId()) {
return 1;
} else {
return 0;
}
}
$selectedCategory = array_intersect_ukey(
$this>request>getParam('category_id'),
$categories,
'key_compare_func'
)
For more information on the different array functions you can look at the PHP manual

OO way or functional way of string comparison conditionals in php

I am curling on a specific page that returns only html. To determine what page it returns, I simply try to stripos the result of the curl
Like so:
$result = curl_exec($ch);
if(stripos($result, 'success') !== false) {
// do something
} else {
if (stripos($result, 'foo') !== false) {
// do something
} else if (stripos($result, 'foo') !== false) {
// do something
} else if (stripos($result, 'bar') !== false) {
// do something
} else if (stripos($result, 'bazz') !== false) {
// do something
} else {
// do something
}
}
This is quite messy I think, is there an OO way or functional way to solve this kind of problem if I were looking at minimal if statements or ultimately an if-less code.
What you are searching for a ways of abstraction. In this example you are repeating yourself in case analysis and this might be the best approach if the "do something" is very different and not consistent.
$map = [ 'success' => function () { return 1; },
'foo' => function () { return 2; },
'bar' => function () { return 3; },
'bazz' => function () { return 4; } ];
foreach ( $map as $search => $value )
{
if (stripos($result, $search) !== false )
{
return call_user_func($value);
}
}
In my example these could just have been constants and we could just return them instead of applying a function. In a functional pattern this would be like the function any in Scheme SRFI-1 except it returns it's true value:
// This function uses PHP 5.6 ellipsis
function array_any(callable $callable, ...$arrays) {
if( count($arrays) == 1 ) {
$args_zipped = array_map( function ($x) { return [$x]; }, $arrays[0]);
} else {
array_unshift( $arrays, null);
$args_zipped = call_user_func_array( "array_map", $arrays);
}
foreach ( $args_zipped as $args ) {
$result = call_user_func_array($callable, $args);
if( $result !== false )
return $result;
}
return false;
}
array_any( function ($search, $value) {
if ( stripos($result, $search) !== false )
return $value;
return false;
},
array_keys($map),
array_values($map));
The function in itself uses linear update, but as you can see it works similar to array_map.
This simple function would do that work:
function checkWord ($haystack,$needle){
foreach ($needle as $word) {
if (stripos($haystack, $word) !== false) {
echo $word." was found!<br/>";
}
else{
echo $word." wasn't found<br/>";
}
}
}
checkWord("Hello what's up?",array('Hello','Huhud','up','?'));
This will output:-
Hello was found!
Huhud wasn't found
up was found!
? was found!

php function return a Boolean and use it on condition

im not sure on how i am going to explain this correctly.
I wanted a function to validate a string which i figured correctly.
But i want the function to return a boolean value.
And outside a function i need to make a condition that if the function returned false, or true that will do something. Here's my code.
i am not sure if this is correct.
<?php
$string1 = 'hi';
function validatestring($myString, $str2) {
if(!empty($myString)) {
if(preg_match('/^[a-zA-Z0-9]+$/', $str2)) {
}
}
else {
return false;
}
}
if(validatestring == FALSE) {
//put some codes here
}
else {
//put some codes here
}
?>
EDIT : Now what if there are more than 1 condition inside the function?
<?php
$string1 = 'hi';
function validatestring($myString, $myString2) {
if(!empty($myString)) {
if(preg_match('/^[a-zA-Z0-9]+$/', $str2)) {
return true;
}
else {
retun false;
}
}
else {
return false;
}
}
if(validatestring($myString, $myString2) === FALSE) {
//put some codes here
}
else {
//put some codes here
}
?>
Functions need brackets and parameter. You dont have any of them.
This would be correct:
if(validatestring($myString) === false) {
//put some codes here
}
An easier and more elegant method would be this:
if(!validatestring($myString)) {
//put some codes here
}
<?php
$string1 = 'hi';
function validatestring($myString) {
if(!empty($myString)) {
return true;
}
else {
return false;
}
}
if(validatestring($string1) === FALSE) {
//put some codes here
}
else {
//put some codes here
}
?>
Sidenote, since empty() already returns false ,you could simplify by doing:
function validateString($string){
return !empty($string);
}
if(validateString($myString){
// ok
}
else {
// not ok
}
To make a check and test later:
$check = validateString($myString);
if($check){ }
There's no need to check == false or === false, the function already returns a boolean, it would be redundant.
store $string1 to $myString in the function
myString=string1
<?php
$string1 = 'hi';
function validatestring($myString) {
myString=string1;
if(!empty($myString)) {
return true;
}
else {
return false;
}
}
if(validatestring() === FALSE) {
//put some codes here
}
else {
//put some codes here
}
?>

Return with ternary expression breaks foreach loop on first iteration

Ok, i tested what follows and i'll just let you know what i discovered:
echo ('-1' < 0) ? 'true' : 'false'; // will echo "true"
echo ('1' > 0) ? 'true' : 'false'; // will echo "true"
# Notice that '-1' and '1' are strings
Now let's take an array, coming from the database after filtering all the result in order to get only rows with UID = 1.
$this->a = array(
[0] => array(
'UID' => '1',
'PID' => '91',
'Amount' => '-1'
),
[1] => array(
'UID' => '1',
'PID' => '92',
'Amount' => '1'
),
[2] => array(
'UID' => '1',
'PID' => '93',
'Amount' => '1'
)
);
Now i want to create a function posAmount($PID) that returns true if 'Amount' > 0 or false if 'Amount' < 0. (Notice: Amount = 0 is something i don't really care). Also i'd like to write as similar function called negAmount($PID) that returns the exactely opposite of the first. I'd like, now, to introduce you to my twin functions:
public function posAmount($pid)
{
foreach ($this->a as $a)
{
if (count($this->a) == 0) { return false; }
return ($a['PID'] == $pid and $a['Amount'] > 0) ? true : false;
}
}
public function negAmount($pid)
{
foreach ($this->a as $a)
{
if (count($this->a) == 0) { return false; }
return ($a['PID'] == $pid and $a['Amount'] < 0) ? true : false;
}
}
The cool fact is that, regarding the first array (which, i checked with var_dump() keeps its nature trough the entire script):
$istance->negAmount(91); // Returns true, as expected
$istance->posAmount(92); // Returns false, as NOT expected.
# Why do God wants me to get mad?
The problem is that you are always returning on the first iteration of the foreach loop. You should rewrite the functions like this:
public function negAmount($pid) {
if (count($this->a) == 0) { return false; }
foreach ($this->a as $a) {
if ($a['PID'] == $pid) {
if ($a['Amount'] < 0) {
return true;
}
}
}
return false;
}
public function posAmount($pid) {
if (count($this->a) == 0) { return false; }
foreach ($this->a as $a) {
if ($a['PID'] == $pid) {
if ($a['Amount'] > 0) {
return true;
}
}
}
return false;
}
May just be a typo in your demo code, but posAmount method is looping $this->a, whereas the other is looping $this->votes - OP corrected
You've got some odd things in your code. Why are you checking the count of $this->a from within a foreach loop? It would make more sense to check the count before you start looping.
Also, you've got some logic errors in your comparison. You're only comparing the first iteration through the loop... it will either return true or false for the first index of the array and never even look at the others. You'll want to match the PID in the loop before you compare - and return - any thing. Like so:
public function posAmount($pid)
{
if (count($this->a) == 0) { return false; }
foreach ($this->votes as $a) {
if ($a['PID'] == $pid)
return $a['Amount'] > 0 ? true : false;
}
return false;
}
public function posAmount($pid)
{
if (count($this->a) == 0) { return false; }
foreach ($this->votes as $a) {
if ($a['PID'] == $pid)
return $a['Amount'] < 0 ? true : false;
}
return false;
}
The problem is you're trying to compare a string to an int without trying to convert it. Change $a['Amount'] to (int)$a['Amount'] and see what happens.
So here you iterate $this->a:
public function posAmount($pid)
{
foreach ($this->a as $a)
But here $this->votes:
public function posAmount($pid)
{
foreach ($this->a as $a)
Typo or what...

Categories