How to get the values only if all the keys have matched? - php

I want to make a method that returns keys and values. But only if the keys include the following string "_1" and "__last".
If only one matches then exit the function, only if the two string are included in the key, return the key with the value for a weather.
$infoList = array("_key_1"=>array("time"=>9, "day"=>"Tuesday", "weather"=>"sunny",
"humidity"=>"80%"),
"_key_2"=>array("time"=>5, "day"=>"Tuesday", "weather"=>"cloudy"),
"_key__last"=>array("time"=>3, "day"=>"Sunday", "weather"=>"rainy"))
public function getData() {
$list = array();
foreach($infoList as $key){
if(preg_match('/(_key)_(_1)/', $key) && preg_match('/(_key)_(__last)/', $key) == TRUE){
$list[$key] = $list[$key]["weather"]
}
}
return $list
}

You are making your life so much more difficult that it need be, use str_contains() its easier than building complex REGEX's and getting very confused by the look of it :)
I also fixed a number of other mistakes, such as the foreach that was not going to work, so check all the code.
It is also better to pass data to a function/method otherwise you get into scoping issues!
$infoList = array("_key_1"=>array("time"=>9, "day"=>"Tuesday", "weather"=>"sunny", "humidity"=>"80%"),
"_key_2"=>array("time"=>5, "day"=>"Tuesday", "weather"=>"cloudy"),
"_key__last"=>array("time"=>3, "day"=>"Sunday", "weather"=>"rainy"));
function getData(Array $infoList) {
$list = [];
$found = 0;
foreach($infoList as $key => $val) {
if( str_contains($key, '_1') || str_contains($key, '__last') ) {
$list[$key] = $val["weather"];
$found++;
}
}
if ( $found >= 2 ) {
return $list;
} else {
return false;
}
}
$res = getData($infoList);
if ( $res !== false ){
print_r($res);
} else {
echo 'Not Found';
}
RESULTS
Array
(
[_key_1] => sunny
[_key__last] => rainy
)

If you want to stick with RegEx, you can use positive lookaheads, the same way you check for passwords characters :
<?php
$pattern = '/^(?=.*_1)(?=.*_last).*$/';
$shouldMatch = [
'_1_last',
'foo_1bar_lasthello',
'_last_1',
'foo_lastbar_1hello'
];
echo 'next ones should match : ' . PHP_EOL;
foreach ($shouldMatch as $item)
{
if (preg_match($pattern, $item))
echo $item . PHP_EOL;
}
$shouldNOTMatch = [
'_2_first',
'bar_lasthello',
'foo_las_1hello'
];
echo 'next ones should NOT match : ' . PHP_EOL;
foreach ($shouldNOTMatch as $item)
{
// v------------ check
if (!preg_match($pattern, $item))
echo $item . PHP_EOL;
}
Output :
next ones should match :
_1_last
foo_1bar_lasthello
_last_1
foo_lastbar_1hello
next ones should NOT match :
_2_first
bar_lasthello
foo_las_1hello

Related

PHP get possible string combination of given array which match with given string

I have an array which contains bunch of strings, and I would like to find all of the possible combinations no matter how it's being sorted that match with given string/word.
$dictionary = ['flow', 'stack', 'stackover', 'over', 'code'];
input: stackoverflow
output:
#1 -> ['stack', 'over', 'flow']
#2 -> ['stackover', 'flow']
What I've tried is, I need to exclude the array's element which doesn't contain in an input string, then tried to match every single merged element with it but I'm not sure and get stuck with this. Can anyone help me to figure the way out of this? thank you in advance, here are my code so far
<?php
$dict = ['flow', 'stack', 'stackover', 'over', 'code'];
$word = 'stackoverflow';
$dictHas = [];
foreach ($dict as $w) {
if (strpos($word, $w) !== false) {
$dictHas[] = $w;
}
}
$result = [];
foreach ($dictHas as $el) {
foreach ($dictHas as $wo) {
$merge = $el . $wo;
if ($merge == $word) {
} elseif ((strpos($word, $merge) !== false) {
}
}
}
print_r($result);
For problems like this you want to use backtracking
function splitString($string, $dict)
{
$result = [];
//if the string is already empty return empty array
if (empty($string)) {
return $result;
}
foreach ($dict as $idx => $term) {
if (strpos($string, $term) === 0) {
//if the term is at the start of string
//get the rest of string
$substr = substr($string, strlen($term));
//if all of string has been processed return only current term
if (empty($substr)) {
return [[$term]];
}
//get the dictionary without used term
$subDict = $dict;
unset($subDict[$idx]);
//get results of splitting the rest of string
$sub = splitString($substr, $subDict);
//merge them with current term
if (!empty($sub)) {
foreach ($sub as $subResult) {
$result[] = array_merge([$term], $subResult);
}
}
}
}
return $result;
}
$input = "stackoverflow";
$dict = ['flow', 'stack', 'stackover', 'over', 'code'];
$output = splitString($input, $dict);

i dont want to display comma after displaying last value

Display comma after displaying last value:
$len = count($boltpatterns);
foreach ($boltpatterns as $key => $boltpattern) {
$st1=$boltpattern['BP'];
$st2='-';
$pos=strpos($st1,$st2);
if($pos === false){
} else {
echo $st1;
if($key != $len - 1) {
echo ',';
}
}
}
You could have simply used array_column() and implode() function.
array_column() lists all your 'BP' keys into one single dimensional array.
implode() converts this single dimensional array $arr into string, separating each entry with a comma.
$arr = array_column($boltpatterns, 'BP');
echo implode(',', $arr);
Just add a new variable that will keep track of how many items you have looped through.
$len = count($boltpatterns);
$count = 1;
foreach ($boltpatterns as $key => $boltpattern) {
$st1=$boltpattern['BP'];
$st2='-';
$pos=strpos($st1,$st2);
if($pos === false){
} else {
echo $st1;
if($count != $len) {
echo ',';
}
}
++$count;
}
You can do this like this,
$valid_data = array();
foreach ($boltpatterns as $key => $boltpattern) {
if ( false !== strpos($boltpattern['BP'],'-') ){
$valid_data[] = $boltpattern['BP'];
}
}
echo implode(", ", $valid_data);
Explanation: Here we collect all the valid date we need to display to a new array. And we use PHP inbuilt function to display them.
Hope this will help you.
$arr = array_column($boltpatterns, 'BP');
echo rtrim(implode(', ', $arr), ', ');
This is an improved version of #object-manipulator's code, with rtrim removing the trailing comma.

How to compare two arrays using a for loop?

I have 2 explode arrays from the database. and this is what i did.
$searches = explode(',', $searchengine);
$icons = explode(',', $icon);
$b = count($searches);
$c = count($icons);
I also made an array to compare each explode array to.
$searchesa = array("google","yahoo","bing");
$d = count($searchesa);
$iconsa = array("facebook","twitter","googleplus","linkedin","pinterest","delicious","stumbleupon","diigo");
$y = count($iconsa);
Then i used for loops to travel to different array indexes. But the result is wrong, and sometimes I have an error which says UNDEFINED OFFSET.
for ($a=0; $a <$d ; $a++) {
if ($searches[$a] == $searchesa[$a])
{echo '<br>'.$searchesa[$a].': check ';
}else
echo '<br>'.$searchesa[$a].': chok ';
}
for ($x=0; $x <$y ; $x++) {
if ($icons[$x] == $iconsa[$x])
echo '<br>'.$iconsa[$x].': check ';
else
echo '<br>'.$iconsa[$x].': chok ';
}
If the index from the database and the array I made are the same, it will state check, else it will state chok.
$arraysAreEqual = ($a == $b); // TRUE if $a and $b have the same key/value pairs.
$arraysAreEqual = ($a === $b); // TRUE if $a and $b have the same key/value pairs in the same order and of the same types.
taken via :
PHP - Check if two arrays are equal
I posted this in my comment, but I suppose the outline will work better in an answer.
I hope this could be of any help:
<?php
$array_a = ['test','test2']; // assume this is your first array
$array_b = ['test']; // assume this is the array you wan to compare against
$found = false;
foreach ($array_a as $key_a => $val_a) {
$found = false;
foreach ($array_b as $key_b => $val_b) {
if ($val_a == $val_b) {
echo '<br>'. $val_b .': check ';
$found = true;
}
}
if (!$found)
echo '<br>'. $val_a .': chok ';
}
?>
EDIT: Please excuse me for not testing it.
This thing will loop through the first array, and compare it with every value in the other array.
Tip: You can easily put this in a function and call it like compare($arr1, $arr2)
You can try in_array method:
$searchesa = array("google","yahoo","bing");
$iconsa = array("facebook","twitter","googleplus","linkedin","pinterest","delicious","stumbleupon","diigo",'google');
foreach($searchesa as $val){
if(in_array($val, $iconsa)){
echo "check";
} else {
echo "choke";
}
}
Note: I've added "google" in $iconsa array.
If I understand you correctly this is what you are looking for:
// Lets prepare the arrays
$searchEngines = explode(',', $searchengine);
$icons = explode(',', $icon);
// Now let's define the arrays to match with
$searchEnginesCompare = array(
'google',
'yahoo',
'bing'
);
$iconsCompare = array(
'facebook',
'twitter',
'googleplus',
'linkedin',
'pinterest',
'delicious',
'stumbleupon',
'diigo'
);
// Check the search engines
foreach ($searchEngines as $k => $searchEngine) {
if (in_array($searchEngine, $searchEnginesCompare)) {
echo $searchEngine." : check<br />";
} else {
echo $searchEngine." : failed<br />";
}
}
// Now let's check the icons array
foreach ($icons as $k => $icon) {
if (in_array($icon, $iconsCompare)) {
echo $icon." : check<br />";
} else {
echo $icon." : failed<br />";
}
}

PHP check if a variable is LIKE an item in an array using in_array

I am creating this array with the below code:
$ignored = array();
foreach(explode("\n", $_POST["ignored"]) as $ignored2) {
$ignored[] = $ignored2;
}
and i want to check if any item inside the array is LIKE a variable. I have this so far:
if(in_array($data[6], $ignored)) {
but I'm not sure what to do with the LIKE
in_array() doesn't provide this type of comparison. You can make your own function as follows:
<?php
function similar_in_array( $sNeedle , $aHaystack )
{
foreach ($aHaystack as $sKey)
{
if( stripos( strtolower($sKey) , strtolower($sNeedle) ) !== false )
{
return true;
}
}
return false;
}
?>
You can use this function as:
if(similar_in_array($data[6], $ignored)) {
echo "Found"; // ^-search ^--array of items
}else{
echo "Not found";
}
Function references:
stripos()
strtolower()
in_array()
Well, like is actually from SQL world.
You can use something like this:
$ignored = array();
foreach(explode("\n", $_POST["ignored"]) as $ignored2) {
$ignored[] = $ignored2;
if ( preg_match('/^[a-z]+$/i', $ignored2) ) {
//do what you want...
}
}
UPDATE: Well, I found this answer, may be it's what you need:
Php Search_Array using Wildcard
Here is a way to do it that can be customized fairly easily, using a lambda function:
$words = array('one','two','three','four');
$otherwords = array('three','four','five','six');
while ($word = array_shift($otherwords)) {
print_r(array_filter($words, like_word($word)));
}
function like_word($word) {
return create_function(
'$a',
'return strtolower($a) == strtolower(' . $word . ');'
);
}
http://codepad.org/yAyvPTIq
To add different checks, simply add more conditions to the return. To do it in a single function call:
while ($word = array_shift($otherwords)) {
print_r(find_like_word($word, $words));
}
function find_like_word($word, $words) {
return array_filter($words, like_word($word));
}
function like_word($word) {
return create_function(
'$a',
'return strtolower($a) == strtolower(' . $word . ');'
);
}

Find the last element of an array while using a foreach loop in PHP

I am writing a SQL query creator using some parameters. In Java, it's very easy to detect the last element of an array from inside the for loop by just checking the current array position with the array length.
for(int i=0; i< arr.length;i++){
boolean isLastElem = i== (arr.length -1) ? true : false;
}
In PHP they have non-integer indexes to access arrays. So you must iterate over an array using a foreach loop. This becomes problematic when you need to take some decision (in my case to append or/and parameter while building query).
I am sure there must be some standard way of doing this.
How do you solve this in PHP?
It sounds like you want something like this:
$numItems = count($arr);
$i = 0;
foreach($arr as $key=>$value) {
if(++$i === $numItems) {
echo "last index!";
}
}
That being said, you don't -have- to iterate over an "array" using foreach in php.
You could get the value of the last key of the array using end(array_keys($array)) and compare it to the current key:
$last_key = end(array_keys($array));
foreach ($array as $key => $value) {
if ($key == $last_key) {
// last element
} else {
// not last element
}
}
Note: This doesn't work because calling next() advances the array pointer, so you're skipping every other element in the loop
why so complicated?
foreach($input as $key => $value) {
$ret .= "$value";
if (next($input)==true) $ret .= ",";
}
This will add a , behind every value except the last one!
When toEnd reaches 0 it means it is at the last iteration of the loop.
$toEnd = count($arr);
foreach($arr as $key=>$value) {
if (0 === --$toEnd) {
echo "last index! $value";
}
}
The last value is still available after the loop, so if you just want to use it for more stuff after the loop this is better:
foreach($arr as $key=>$value) {
//something
}
echo "last index! $key => $value";
If you do not want to treat the last value as special inside loops. This should be faster if you have large arrays. (If you reuse the array after the loop inside the same scope you have to "copy" the array first).
//If you use this in a large global code without namespaces or functions then you can copy the array like this:
//$array = $originalArrayName; //uncomment to copy an array you may use after this loop
//end($array); $lastKey = key($array); //uncomment if you use the keys
$lastValue = array_pop($array);
//do something special with the last value here before you process all the others?
echo "Last is $lastValue", "\n";
foreach ($array as $key => $value) {
//do something with all values before the last value
echo "All except last value: $value", "\n";
}
//do something special with the last value here after you process all the others?
echo "Last is $lastValue", "\n";
And to answer your original question "in my case to append or/and parameter while building query"; this will loop over all the values, then join them together to a string with " and " between them but not before the first value or after the last value:
$params = [];
foreach ($array as $value) {
$params[] = doSomething($value);
}
$parameters = implode(" and ", $params);
There are already many answers, but it's worth to look into iterators as well, especially as it has been asked for a standard way:
$arr = range(1, 3);
$it = new CachingIterator(new ArrayIterator($arr));
foreach($it as $key => $value)
{
if (!$it->hasNext()) echo 'Last:';
echo $value, "\n";
}
You might find something that does work more flexible for other cases, too.
One way could be to detect if the iterator has next. If there is no next attached to the iterator it means you are in the last loop.
foreach ($some_array as $element) {
if(!next($some_array)) {
// This is the last $element
}
}
SINCE PHP 7.3 :
You could get the value of the last key of the array using array_key_last($array) and compare it to the current key:
$last_key = array_key_last($array);
foreach ($array as $key => $value) {
if ($key == $last_key) {
// last element
} else {
// not last element
}
}
to get first and last element from foreach array
foreach($array as $value) {
if ($value === reset($array)) {
echo 'FIRST ELEMENT!';
}
if ($value === end($array)) {
echo 'LAST ITEM!';
}
}
So, if your array has unique array values, then determining last iteration is trivial:
foreach($array as $element) {
if ($element === end($array))
echo 'LAST ELEMENT!';
}
As you see, this works if last element is appearing just once in array, otherwise you get a false alarm. In it is not, you have to compare the keys (which are unique for sure).
foreach($array as $key => $element) {
end($array);
if ($key === key($array))
echo 'LAST ELEMENT!';
}
Also note the strict coparision operator, which is quite important in this case.
Don't add a comma after the last value:
The array:
$data = ['lorem', 'ipsum', 'dolor', 'sit', 'amet'];
The function:
$result = "";
foreach($data as $value) {
$resut .= (next($data)) ? "$value, " : $value;
}
The result:
print $result;
lorem, ipsum, dolor, sit, amet
You can still use that method with associative arrays:
$keys = array_keys($array);
for ($i = 0, $l = count($array); $i < $l; ++$i) {
$key = $array[$i];
$value = $array[$key];
$isLastItem = ($i == ($l - 1));
// do stuff
}
// or this way...
$i = 0;
$l = count($array);
foreach ($array as $key => $value) {
$isLastItem = ($i == ($l - 1));
// do stuff
++$i;
}
Assuming you have the array stored in a variable...
foreach($array as $key=>$value)
{
echo $value;
if($key != count($array)-1) { echo ", "; }
}
If you need to do something for every element except either the first or the last and only if there is more than one element in the array, I prefer the following solution.
I know there are many solutions above and posted months/one year before mine, but this is something I feel is fairly elegant in its own right. The check every loop is also a boolean check as opposed to a numeric "i=(count-1)" check, which may allow for less overhead.
The structure of the loop may feel awkward, but you can compare it to the ordering of thead (beginning), tfoot (end), tbody (current) in HTML table tags.
$first = true;
foreach($array as $key => $value) {
if ($first) {
$first = false;
// Do what you want to do before the first element
echo "List of key, value pairs:\n";
} else {
// Do what you want to do at the end of every element
// except the last, assuming the list has more than one element
echo "\n";
}
// Do what you want to do for the current element
echo $key . ' => ' . $value;
}
For instance, in web development terms, if you want to add a border-bottom to every element except the last in an unordered list (ul), then you can instead add a border-top to every element except the first (the CSS :first-child, supported by IE7+ and Firefox/Webkit supports this logic, whereas :last-child is not supported by IE7).
You can feel free to reuse the $first variable for each and every nested loop as well and things will work just fine since every loop makes $first false during the first process of the first iteration (so breaks/exceptions won't cause issues).
$first = true;
foreach($array as $key => $subArray) {
if ($first) {
$string = "List of key => value array pairs:\n";
$first = false;
} else {
echo "\n";
}
$string .= $key . '=>(';
$first = true;
foreach($subArray as $key => $value) {
if ($first) {
$first = false;
} else {
$string .= ', ';
}
$string .= $key . '=>' . $value;
}
$string .= ')';
}
echo $string;
Example output:
List of key => value array pairs:
key1=>(v1_key1=>v1_val1, v1_key2=>v1_val2)
key2=>(v2_key1=>v2_val1, v2_key2=>v2_val2, v2_key3=>v2_val3)
key3=>(v3_key1=>v3_val1)
This should be the easy way to find the last element:
foreach ( $array as $key => $a ) {
if ( end( array_keys( $array ) ) == $key ) {
echo "Last element";
} else {
echo "Just another element";
}
}
Reference : Link
I have a strong feeling that at the root of this "XY problem" the OP wanted just implode() function.
As your intention of finding the EOF array is just for the glue. Get introduced to the below tactic. You need not require the EOF:
$given_array = array('column1'=>'value1',
'column2'=>'value2',
'column3'=>'value3');
$glue = '';
foreach($given_array as $column_name=>$value){
$where .= " $glue $column_name = $value"; //appending the glue
$glue = 'AND';
}
echo $where;
o/p:
column1 = value1 AND column2 = value2 AND column3 = value3
How about using "end"?
http://php.net/manual/en/function.end.php
It sounds like you want something like this:
$array = array(
'First',
'Second',
'Third',
'Last'
);
foreach($array as $key => $value)
{
if(end($array) === $value)
{
echo "last index!" . $value;
}
}
$array = array("dog", "rabbit", "horse", "rat", "cat");
foreach($array as $index => $animal) {
if ($index === array_key_first($array))
echo $animal; // output: dog
if ($index === array_key_last($array))
echo $animal; // output: cat
}
you can do a count().
for ($i=0;$i<count(arr);$i++){
$i == count(arr)-1 ? true : false;
}
or if you're looking for ONLY the last element, you can use end().
end(arr);
returns only the last element.
and, as it turns out, you CAN index php arrays by integers. It's perfectly happy with
arr[1];
You could also do something like this:
end( $elements );
$endKey = key($elements);
foreach ($elements as $key => $value)
{
if ($key == $endKey) // -- this is the last item
{
// do something
}
// more code
}
I kinda like the following as I feel it is fairly neat. Let's assume we're creating a string with separators between all the elements: e.g. a,b,c
$first = true;
foreach ( $items as $item ) {
$str = ($first)?$first=false:", ".$item;
}
Here's my solution:
Simply get the count of your array, minus 1 (since they start in 0).
$lastkey = count($array) - 1;
foreach($array as $k=>$a){
if($k==$lastkey){
/*do something*/
}
}
foreach ($array as $key => $value) {
$class = ( $key !== count( $array ) -1 ) ? " class='not-last'" : " class='last'";
echo "<div{$class}>";
echo "$value['the_title']";
echo "</div>";
}
Reference
If it is a single dimensional array you can do this to keep it short and sweet:
foreach($items as $idx => $item) {
if (!isset($items[$idx+1])) {
print "I am last";
}
}
Here's another way you could do it:
$arr = range(1, 10);
$end = end($arr);
reset($arr);
while( list($k, $v) = each($arr) )
{
if( $n == $end )
{
echo 'last!';
}
else
{
echo sprintf('%s ', $v);
}
}
If I understand you, then all you need is to reverse the array and get the last element by a pop command:
$rev_array = array_reverse($array);
echo array_pop($rev_array);
You could also try this to make your query... shown here with INSERT
<?php
$week=array('one'=>'monday','two'=>'tuesday','three'=>'wednesday','four'=>'thursday','five'=>'friday','six'=>'saturday','seven'=>'sunday');
$keys = array_keys($week);
$string = "INSERT INTO my_table ('";
$string .= implode("','", $keys);
$string .= "') VALUES ('";
$string .= implode("','", $week);
$string .= "');";
echo $string;
?>
For SQL query generating scripts, or anything that does a different action for the first or last elements, it is much faster (almost twice as fast) to avoid using unneccessary variable checks.
The current accepted solution uses a loop and a check within the loop that will be made every_single_iteration, the correct (fast) way to do this is the following :
$numItems = count($arr);
$i=0;
$firstitem=$arr[0];
$i++;
while($i<$numItems-1){
$some_item=$arr[$i];
$i++;
}
$last_item=$arr[$i];
$i++;
A little homemade benchmark showed the following:
test1: 100000 runs of model morg
time: 1869.3430423737 milliseconds
test2: 100000 runs of model if last
time: 3235.6359958649 milliseconds
Another way to go is to remember the previous loop cycle result and use that as the end result:
$result = $where = "";
foreach ($conditions as $col => $val) {
$result = $where .= $this->getAdapter()->quoteInto($col.' = ?', $val);
$where .= " AND ";
}
return $this->delete($result);

Categories