How to compare two arrays using a for loop? - php

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

Related

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

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

Exactly one occurence of value in array

I'm trying to find a native php function which returns true if there is exactly one occurrence of any given element in an array.
For example:
$searchedForValue = 3;
$array1 = [1,2,3,4,5,6];
$array2 = [1,2,3,3,4,5];
$array3 = [1,2,4,5,6];
oneOccurrence($array1,$searchedForValue);
oneOccurrence($array2,$searchedForValue);
oneOccurrence($array3,$searchedForValue);
This should return:
true
false
false
Cheers
You should use array_count_values() here.
$array_values = array_count_values($array2);
This will return an array. Key denotes each element of $array2 and value denotes frequency of each element.:
Array (
[1] => 1
[2] => 1
[3] => 2 // Denotes 3 appears 2 times
[4] => 1
[5] => 1
)
if (#$array_values[$searchedForValue] == 1) {
echo "True";
} else {
echo "False";
}
This does what you want. Bare in mind, echoing oneOccurence won't output 'true' or 'false', it returns a boolean.
function oneOccurrence ($arr, $val) {
$occurrences = [];
foreach ($arr as $v) {
if ($v == $val) {
$occurrences[] = $v;
}
}
return count($occurrences) == 1;
}
P.S echo doesn't need brackets as it's a PHP construct.
A small utility function - count array values using array_count_values and then if the search key exists and if its count is exactly 1, return true otherwise false:
function oneOccurrence($array, $searchValue) {
$array = array_count_values($array);
return (array_key_exists($searchValue, $array) && $array[$searchValue]==1)?true:false;
}
Check EVAL
Since you are searching for one occurrence: http://codepad.org/cZImb4FI
Use array_count_values()
<?php
$searchedForValue = 3;
$array1 = array(1,2,3,4,5,6);
$array2 = array(1,2,3,3,4,5);
$array3 = array(1,2,4,5,6);
$arr = array($array1,$array2 ,$array3);
function array_count_values_of($value, $array) {
$counts = array_count_values($array);
return $counts[$value];
}
foreach($arr as $ar){
if( array_count_values_of($searchedForValue,$ar)==1){echo "true";}else{echo "false";}
}
?>
output
true false false
//In Php in_array() function is provided..
$searchedForValue = 3;
$array1 = array(1,2,3,4,5,6);
$array2 = array(1,2,3,3,4,5);
$array3 = array(1,2,4,5,6);
if(in_array($searchedForValue,$array1))
{
echo "true";
}
else
{
echo "false";
}
if(in_array($searchedForValue,$array2))
{
echo "true";
}
else
{
echo "false";
}
if(in_array($searchedForValue,$array3))
{
echo "true";
}
else
{
echo "false";
}

extract values found in array from string

I am stuck. What I would like to do: In the $description string I would like to check if any of the values in the different arrays can be found. If any of the values match, I need to know which one per array. I am thinking that I need to do a function for each $a, $b and $c, but how, I don't know
if($rowGetDesc = mysqli_query($db_mysqli, "SELECT descFilter FROM tbl_all_prod WHERE lid = 'C2'")){
if (mysqli_num_rows($rowGetDesc) > 0){
while($esk= mysqli_fetch_array($rowGetDesc)){
$description = sanitizingData($esk['descFilter']);
$a = array('1:100','1:250','1:10','2');
$a = getExtractedValue($a,$description);
$b = array('one','five','12');
$b = getExtractedValue($b,$description);
$c = array('6000','8000','500');
$c = getExtractedValue($c,$description);
}
}
}
function getExtractedValue($a,$description){
?
}
I would be very very greatful if anyone could help me with this.
many thanks Linda
It would be better to create each array just once and not in every iteration of the while loop.
Also using the same variable names in the loop is not recommended.
if($rowGetDesc = mysqli_query($db_mysqli, "SELECT descFilter FROM tbl_all_prod WHERE lid = 'C2'")){
if (mysqli_num_rows($rowGetDesc) > 0){
$a = array('1:100','1:250','1:10','2');
$b = array('one','five','12');
$c = array('6000','8000','500');
while($esk= mysqli_fetch_array($rowGetDesc)){
$description = sanitizingData($esk['descFilter']);
$aMatch = getExtractedValue($a,$description);
$bMatch = getExtractedValue($b,$description);
$cMatch = getExtractedValue($c,$description);
}
}
}
Use strpos to find if the string exists (or stripos for case insensitive searches). See http://php.net/strpos. If the string exists it will return the matching value in the array:
function getExtractedValue($a,$description) {
foreach($a as $value) {
if (strpos($description, $value) !== false) {
return $value;
}
}
return false;
}
there s a php function for that which return a boolean.
or if you wanna check if one of the element in arrays is present in description, maybe you 'll need to iterate on them
foreach($array as element){
if(preg_match("#".$element."#", $description){
echo "found";
}
}
If your question is correctly phrased and indeed you are searching a string, you should try something like this:
function getExtractedValue($a, $description) {
$results = array();
foreach($a as $array_item) {
if (strpos($array_item, $description) !== FALSE) {
$results[] = $array_item;
}
}
return $results;
}
The function will return an array of the matched phrases from the string.
Try This..
if ( in_array ( $str , $array ) ) {
echo 'It exists'; } else {
echo 'Does not exist'; }

Checking array against another array

Say I have the following two arrays:
$array = Array("Julie","Clive","Audrey","Tom","Jim","Ben","Dave","Paul");
$mandt = Array(1,0,0,1,0,0,1,1);
The numbers signify whether the names are valid or not. 1 is valid 0 is not. I need to check through the names and echo their name and then "true" if the name is valid and "false" if it is not, i.e:
Julie: True
Clive: False
Audry: False
Etc...
Could anybody help me out please?
THanks.
So something like this foreach() loop?...
foreach($array as $key => $value){
echo $value.": ";
echo $mandt[$key] ? "True" : "False";
echo "<br />";
}
$values = array_combine($array, $mandt);
$values = array_map(function ($i) { return $i ? 'True' : 'False'; }, $values);
var_dump($values);
// or loop through them, or whatever
for($i=0, $count=count($array); $i<$count; $i++){
echo $array[$i] . ": " . ($mandt[$i]? "True":"False") . "<br/>";
}
Why don't you just loop through the arrays?
$array = Array("Julie","Clive","Audrey","Tom","Jim","Ben","Dave","Paul");
$mandt = Array(1,0,0,1,0,0,1,1);
$c = count($array);
for ($i = 0; i < $c; i++) {
echo $array[$i] . ": " . (($mandt[$i] == 1)?"True":"False") . "\n";
}
Instead of looping and comparing the arrays, you could make a Hashtable-like array, like this:
$arr = array(
"Julie" => true,
"Clive" => false,
"Audrey" => false,
"Tom" => true
[...]
);
This way, you can just run something like that:
if ($arr["Julie"]) {
//Julie is a valid name!
} else {
//Julie is not a valid name!
}
This would be way more efficient than looping through the array.

How to skip the 1st key in an array loop?

I have the following code:
if ($_POST['submit'] == "Next") {
foreach($_POST['info'] as $key => $value) {
echo $value;
}
}
How do I get the foreach function to start from the 2nd key in the array?
For reasonably small arrays, use array_slice to create a second one:
foreach(array_slice($_POST['info'],1) as $key=>$value)
{
echo $value;
}
foreach(array_slice($_POST['info'], 1) as $key=>$value) {
echo $value;
}
Alternatively if you don't want to copy the array you could just do:
$isFirst = true;
foreach($_POST['info'] as $key=>$value) {
if ($isFirst) {
$isFirst = false;
continue;
}
echo $value;
}
Couldn't you just unset the array...
So if I had an array where I didn't want the first instance,
I could just:
unset($array[0]);
and that would remove the instance from the array.
If you were working with a normal array, I'd say to use something like
foreach (array_slice($ome_array, 1) as $k => $v {...
but, since you're looking at a user request, you don't have any real guarantees on the order in which the arguments might be returned - some browser/proxy might change its behavior or you might simply decide to modify your form in the future. Either way, it's in your best interest to ignore the ordering of the array and treat POST values as an unordered hash map, leaving you with two options :
copy the array and unset the key you want to ignore
loop through the whole array and continue when seeing the key you wish to ignore
in loop:
if ($key == 0) //or whatever
continue;
Alternative way is to use array pointers:
reset($_POST['info']); //set pointer to zero
while ($value=next($_POST['info']) //ponter+1, return value
{
echo key($_POST['info']).":".$value."\n";
}
If you're willing to throw the first element away, you can use array_shift(). However, this is slow on a huge array. A faster operation would be
reset($a);
unset(key($a));
On a array filled with 1000 elements the difference is quite minimal.
Test:
<?php
function slice($a)
{
foreach(array_slice($a, 1) as $key)
{
}
return true;
}
function skip($a)
{
$first = false;
foreach($a as $key)
{
if($first)
{
$first = false;
continue;
}
}
return true;
}
$array = array_fill(0, 1000, 'test');
$t1 = time() + microtime(true);
for ($i = 0; $i < 1000; $i++)
{
slice($array);
}
var_dump((time() + microtime(true)) - $t1);
echo '<hr />';
$t2 = time() + microtime(true);
for ($i = 0; $i < 1000; $i++)
{
skip($array);
}
var_dump((time() + microtime(true)) - $t2);
?>
Output:
float(0.23605012893677)
float(0.24102783203125)
Working Code From My Website For Skipping The First Result and Then Continue.
<?php
$counter = 0;
foreach ($categoriest as $category) { if ($counter++ == 0) continue; ?>
It is working on opencart also in tpl file do like this in case you need.
foreach($_POST['info'] as $key=>$value) {
if ($key == 0) { //or what ever the first key you're using is
continue;
} else {
echo $value;
}
}
if you structure your form differently
<input type='text' name='quiz[first]' value=""/>
<input type='text' name='quiz[second]' value=""/>
...then in your PHP
if( isset($_POST['quiz']) AND
is_array($_POST['quiz'])) {
//...and we'll skip $_POST['quiz']['first']
foreach($_POST['quiz'] as $key => $val){
if($key == "first") continue;
print $val;
}
}
...you can now just loop over that particular structure and access rest normally
How about something like this? Read off the first key and value using key() and current(), then array_shift() to dequeue the front element from the array (EDIT: Don't use array_shift(), it renumbers any numerical indices in the array, which you don't always want!).
<?php
$arr = array(
'one' => "ONE!!",
'two' => "TWO!!",
'three' => "TREE",
4 => "Fourth element",
99 => "We skipped a few here.."
) ;
$firstKey = key( $arr ) ;
$firstVal = current( $arr ) ;
echo( "OK, first values are $firstKey, $firstVal" ) ;
####array_shift( $arr ) ; #'dequeue' front element # BAD! renumbers!
unset( $arr[ $firstKey ] ) ; # BETTER!
echo( "Now for the rest of them" ) ;
foreach( $arr as $key=>$val )
{
echo( "$key => $val" ) ;
}
?>

Categories