PHP foreach with more condition - php

Is it possible to set foreach function more than 2 condition. Example like below:
$stat_cps = $_POST['stat_cp'];
$acc_idss = $_POST['acc_ids'];
$string = 'NG';
foreach ($stat_cps as $url)
{
if(strpos($string, $url) !== FALSE)
{
echo "One of the field is NG";
return true;
}
}
echo "All field is OK";
What I want is:
if $stat_cps or $acc_idss contains NG then echo "One of the field is NG";
On the above code, it's only working for $stat_cps
*stat_cps and acc_idss is from radio button form.
Anyone can give the suggestion?

"One-line" solution with array_merge, implode and strpos functions:
...
$hasNg = strpos("NG", implode(",", array_merge($stat_cps,$acc_idss)));
...
// check for 'NG' occurance
echo ($hasNg !== false)? "One of the field is NG" : "string 'NG' doesn't exists within passed data";

You can use array_merge to combine both your arrays:
http://php.net/manual/en/function.array-merge.php
$stat_cps = $_POST['stat_cp'];
$acc_idss = $_POST['acc_ids'];
$merged = array_merge($stat_cps,$acc_idss);
$string = 'NG';
foreach ($merged as $url)
{
if(strpos($string, $url) !== FALSE)
{
echo "One of the field is NG";
return true;
}
}
This will remove duplicate string keys but it doesn't look like that should be an issue here if you just want one match
From you comment try doing
$stat_cps = $_POST['stat_cp'];
$acc_idss = $_POST['acc_ids'];
$merged = array_merge($stat_cps,$acc_idss);
$match = false;
$string = 'NG';
foreach ($merged as $url)
{
if(strpos($string, $url) !== FALSE)
{
$match = true;
}
}
if($match){
echo "One of the field is NG";
}else{
echo "Everything is OK";
}

$stat_cps = $_POST['stat_cp'];
$acc_idss = $_POST['acc_ids'];
$process=0;
$string = 'NG';
foreach ($stat_cps as $url)
{
if(strpos($string, $url) !== FALSE)
{
$process=1;
}
}
foreach ($acc_idss as $url2)
{
if(strpos($string, $url2) !== FALSE)
{
$process=1;
}
}
if($process==1){
echo "One of the field is NG";
return true;
}

#header user in_array()
$stat_cps = $_POST['stat_cp'];
$acc_idss = $_POST['acc_ids'];
$string = 'NG';
foreach ($stat_cps as $url)
{
if(in_array($string, $url) !== FALSE)
{
echo "One of the field is NG";
return true;
}
}

Related

Find and extract words from strings

I need to find and extract words (array) in a string. I tried many techniques, and I found how to find first occurrences, but can't get it to work recursively.
$uda_state = [
"uda actif",
"uda stagiaire",
"stagiaire uda",
"uda",
"apprenti actra",
"actra apprenti",
"actra"
];
$arr = [
'<p>Nothing here</p>',
'<p>UDA Stagiaire et ACTRA</p>',
'<p>Stagiaire UDA</p>',
'<p>Should not pop</p>'
];
function contains($str, array $arr)
{
foreach($arr as $a) {
if ($pos = stripos($str,$a)) return true;
}
return false;
}
function extractWord($str, array $arr)
{
foreach($arr as $a) {
if ($pos = stripos($str, $a)) return $arr;
}
}
function find_uda_actra($str, array $arr = []) {
global $uda_state;
if (contains($str, $uda_state)) {
$word = extractWord($str, $uda_state);
$arr[] = $word;
$str = str_ireplace($word, '', $str);
if ($str != '') {
if (contains($str, $uda_state)) {
list($str, $arr) = find_uda_actra($str, $arr);
}
else {
return [$str, $arr];
}
} else {
return [$str, $arr];
}
}
return [$str, $arr];
}
foreach ($arr as $str) {
list($content, $uda) = find_uda_actra($str);
echo 'Content:'.PHP_EOL;
var_dump($content);
echo 'UDA:'.PHP_EOL;
var_dump($uda);
}
All I get now is emptied content and the whole $uda_state in each $uda. I need only the one that was found.
3v4l link for sandbox.

Matching wildcard arrays in PHP - WordPress

PHP code:
$search = "Who is KMichaele test";
$array = ["john","michael","adam"];
if (in_array($search, $array)) {
echo "success";
}
else
echo "fail";
I want the success output. How is it possible?
You can use array_reduce and stripos to check all the values in $array to see if they are present in $search in a case-insensitive manner:
$search = "Who is KMichaele test";
$array = ["john","michael","adam"];
if (array_reduce($array,
function ($c, $i) use ($search) {
return $c || (stripos($search, $i) !== false);
},
false))
echo "success";
else
echo "fail";
Output:
success
Edit
Since this is probably more useful wrapped in a function, here's how to do that:
$search = "Who is KMichaele test";
$array = ["john","michael","adam"];
function search($array, $search) {
return array_reduce($array,
function ($c, $i) use ($search) {
return $c || (stripos($search, $i) !== false);
},
false);
}
if (search($array, $search))
echo "success";
else
echo "fail";
$search2 = "michael";
if (search($array, $search2))
echo "success";
else
echo "fail";
Output
success
success
Here's an in_array-esque function that will ignore case and bail early on a match:
function search_array($search, $arr) {
foreach ($arr as $item) {
if (stripos($search, $item) !== false) {
return 1;
}
}
return 0;
}
$search = "Who is KMichaele test";
$array = ["john", "michael", "adam"];
if (search_array($search, $array)) {
echo "success\n";
}
else {
echo "fail\n";
}
Output
success
You can do this with a simple regx
$search = "Who is KMichaele test";
$array = ["john","michael","adam"];
$regex = '/\b('.implode('|', $array).')\b/i';
///\b(john|michael|adam)\b/i
$success = preg_match($regex, $search);
The Regex is simple
\b - matches word boundary
| or
the flag \i, case insensitive
Essential match any of the words in the list.
By using the boundary the word michael will not match kmichael for example. If you want partial word matches, just remove those.
Sandbox without the word boundry
If you include the 3rd argument
$success = preg_match($regex, $search,$match);
You can tell what the matches were. And last but not lest you can reduce it down to one line
$success = preg_match('/\b('.implode('|', $array).')\b/i', $search);

PHP strpos array

I am trying to loop through a string that contains html from a scraped webpage. First I look to return all links that contain the word "result" and then I would like to organize all the links that contain one of four cases, "base", "second", "third" or "latest" and create a fluid array.
Below is what I have come up with but it returns "Warning: strpos(): needle is not a string or an integer". I cannot seem to get the array cases to work.
Any help would be greatly appreciated. Thank you
$key = "results";
$reportKey = array("base", "second", "third","latest");
$keyArray = array();
foreach($html->find('a') as $element){
if (strpos($element->href, $key) !== false){
if (strpos($element->href, $reportKey) !== false){
$keyArray[] = $element->href;
}
}
}
echo "<pre>" . print_r($keyArray) . "</pre> ";
You can't use an array as a needle in strpos. Change second if to:
if (str_replace($reportKey, "", $element->href) === $element->href) {
$keyArray[] = $element->href;
}
strpos() does not allow more than one needle, you can do this:
$key = "results";
$reportKey = array("base", "second", "third","latest");
$keyArray = array();
foreach($html->find('a') as $element)
{
if (strpos($element->href, $key) !== false){
if (
strpos($element->href, $reportKey[0]) !== false
|| strpos($element->href, $reportKey[1]) !== false
|| strpos($element->href, $reportKey[2]) !== false
|| strpos($element->href, $reportKey[3]) !== false
){
$keyArray[] = $element->href;
}
}
}
echo "<pre>" . print_r($keyArray) . "</pre> ";
You could also do your own function, this is only an example:
function multi_strpos($string, $check, $getResults = false)
{
$result = array();
$check = (array) $check;
foreach ($check as $s)
{
$pos = strpos($string, $s);
if ($pos !== false)
{
if ($getResults)
{
$result[$s] = $pos;
}
else
{
return $pos;
}
}
}
return empty($result) ? false : $result;
}
A solution using array_map() and in_array():
$key = 'results';
$reportKey = ['base', 'second', 'third', 'latest'];
$keyArray = [];
foreach($html->find('a') as $element) {
if (false !== strpos($element->href, $key)) {
// I changed the condition here
$pos = array_map(fn($k) => strpos($element->href, $k) !== false, $reportKey);
if (in_array(true, $pos)){
$keyArray[] = $element->href;
}
}
}
$pos will be an array containing booleans based on matches between $element->href and $reportKey items.
Then we check with in_array() if it matched at least one time.

how to find a value contained inside a value inside an array?

If I have the array:
$os = array("Mac", "NT", "Irix", "Linux");
I know that in_array() is what to use if I want to find "Mac" inside $os.
But what I have the array:
$os = array( [1] => "Mac/OSX", [2] => "PC/Windows" );
and I want to see if "Mac" is contained in $os?
Try:
$example = array("Mac/OSX","PC/Windows" );
$searchword = 'Mac';
$matches = array_filter($example, function($var) use ($searchword) { return preg_match("/\b$searchword\b/i", $var); });
You could also use array_map to do this. Take a look at the following code:
$array = array(
'Mac/OSX',
'PC/Windows',
);
$result = in_array(true, array_map(function ($word, $match, $char = "/") {
$words = explode('/', $word);
return in_array($match, $words) ? true : false;
}, $array, array('Mac')));
var_dump($result); // bool(true)
You can try this-
$os = array( "Mac/OSX", "PC/Windows" );
function findInArray($os){
foreach($os as $val){
if(strpos($val, $word_to_search) !== false){
return true;
}
}
return false;
}
Here is another solution:
array_map(function($v){
if (strpos($v, 'Mac') !== false) {
echo 'found';
exit;
}
},$os);
echo "Not found";
DEMO
You can simply use preg_grep function of PHP like as
$os = array( '1' => "Mac/OSX", '2' => "PC/Windows" );
print_R(preg_grep("/Mac/",$os));
Output:
Array ( [1] => Mac/OSX )
By using foreach and strpos
$os =array("Mac/OSX","PC/Windows" );
$string = "Mac";
foreach ($os as $data) {
//echo $data;
if (strpos($data,$string ) !== FALSE) {
echo "Match found";
}else{
echo "not found";
}
}
DEMO
function FindString($string, $os)
{
// put the string in between //
$preg = "/$string/";
// Match found
$found = false;
// loop each value
for($j = 0; $j < count($os); $j++)
{
// check with pattern
if(preg_match($preg,$os[$j]))
{
// set var to ture
$found = true;
// Break
break;
}
}
if($found == false)
{
die("Unable to found the string $string.");
}
echo "String $string found in array index $j and value is $os[$j]";
}
$where =array("Mac/OSX","PC/Windows" );
$what = "Mac";
FindString($what, $where);

strpos with array_key_search

i have a code to search for array keys, but only if the message is the exact message, i want it to use strpos so it can detect the message but i don't know how to do it:
My Code:
$message = $_POST['message'];
$responses = array("hi" => "whats up?");
if (array_key_exists($message,$responses)){
$msg = strtolower($message);
$answer = $responses[$msg];
echo $answer;
}
So this only works if the whole posted data was "hi". I want it to use strpos so it can detect hi anywhere, how would i do that?
I'm not 100% sure, but is this what you want?
$foundKey = null;
foreach ($responses as $key => $value) {
if (strpos($message, $key) !== false) {
$foundKey = $key;
break;
}
}
if ($foundKey !== null) {
echo "Found key: " . $responses[$key];
}
Edit:
If you want a case insensitive version, of course you can use this instead:
$foundKey = null;
foreach ($responses as $key => $value) {
if (stripos($message, $key) !== false) {
$foundKey = strtolower($key);
break;
}
}
if ($foundKey !== null) {
echo "Found key: " . $responses[$key];
}
strpos(firststring,secondstring,startposition[Optional]) function is return num.if num>=0 mean second string in first string.
$message = $_POST['message'];
$responses = array("hi" => "whats up?");
if (strpos($message,$responses)>=0){
$msg = strtolower($message);
$answer = $responses[$msg];
echo $answer;
}

Categories