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!
Related
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;
}
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!";
}
I want to check if the user is using the default settings. In the example below, I'm trying to check if all "foreached" items return true. If a single foreached item doesn't return true, return false on the whole function.
private function is_using_default_settings() {
// returns a huge array with settings
$merged_preset = $this->options_merged();
foreach($merged_preset as $preset) {
if($preset[5] == 1) {
$section = 'general';
} elseif($preset[5] == 2) {
$section = 'advanced';
} elseif($preset[5] == 3) {
$section = 'technical';
}
$option = get_option($section);
if($preset[3] == $option[$preset[0]] && !is_null($preset[1])) {
return true;
}
}
return false;
}
I've been brainstorming for the past few days to get this sorted on my own, but sadly cannot get it to work. What is the best approach to this?
you can check when is false and block the full foreach then return value, if all is true return value true
try this:
private function is_using_default_settings() {
$returnValue = true;
$merged_preset = $this->options_merged();
foreach($merged_preset as $preset) {
if($preset[5] == 1) {
$section = 'general';
} elseif($preset[5] == 2) {
$section = 'advanced';
} elseif($preset[5] == 3) {
$section = 'technical';
}
$option = get_option($section);
if($preset[3] != $option[$preset[0]] || is_null($preset[1])) {
$returnValue = false;
break;
}
}
return $returnValue;
}
You should return false when any check fails in the foreach, otherwise return true.
function check()
{
foreach($arr as $v)
{
//check fails
if(fail of the check)
return false;
}
return true;
}
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
}
?>
Could I do this in PHP?
if ($Var = $this->test1() == true) {
var_dump($Var);
}
public function test1() {
return true;
}
It echoes true, but I'm not sure if this is the correct way to check such return values.
Yes you can, but write:
if (($var = $this->test1()) === true) {
var_dump($var);
}
To be safe and to alert the reader there is something going on.
I wouldn't advise you to do this though, but in some cases this is acceptable; such as a complex if-else tree where lazy execution is desirable.
if (($result = slow_process()) !== false) {
return $result;
} else if (($result = slow_process1()) !== false) {
return $result;
} else if (($result = slow_process2()) !== false) {
return $result;
} else if (($result = slow_process3()) !== false) {
return $result;
}
This is overly simplified, but these situations do occur.
You can but there is 2 things you should be aware of :
When you do something like :
if ($Var = $this->test1() == true) {
The operators are confusing :
do you want to do $this->test1() == true and store result $var
do you want to do $var = $this->test1() and compare it with true
In your case, $this->test1() returns true so it does not matter. But if we change your code a bit :
if ($Var = $this->test1() == 5) {
var_dump($Var);
}
public function test1() {
return 3;
}
Someone who read your code will not understand if you want to store $this->test1() in $Var (so, make 3 in var) or if you want to put result of comparison $this->test1 == 5 in $Var (false).
What remains in $Var at the end may be a very good question at the PHP 5.3 Certification but not in a useful case.
To avoid mistakes, uses parenthesis :
if (($var = $this->test1()) == true) {
You should take care of types :
I give you an example of what could return something castable to true :
function test1() { return true; }
function test2() { return 3; }
function test3() { return 3.42; }
function test4() { return "x"; }
function test5() { return array('x'); } // array() == true returns false
function test6() { return new stdClass(); }
echo test1() == true;
echo test2() == true;
echo test3() == true;
echo test4() == true;
echo test5() == true;
echo test6() == true;
// outputs 111111 (1 = true)
To avoid mistakes, you should use === operator. Your final piece of code becomes :
if (($var = $this->test1()) === true) {
The == true part is unnecessary. What you have is valid syntax, but some find it confusing. You can always do:
$Var = $this->test1();
if ($Var) { ...
Just decide on the standard with your development team.
You can also do:
if ($Var = $this->test1()) {
var_dump($Var);
}
public function test1() {
return true;
}