Compare two arrays and echo difference - php

What is wrong with this code? I've tried using array_udiff without any success.
<?php
#I want to echo values of $paths1 that do not appear (even partially) on $paths2.
$paths1 = array('one', 'two', 'three');
$paths2 = array('twenty one', 'twenty two');
foreach ($paths1 as $path1)
{
foreach ($paths2 as $path2)
{
if (stripos($path1, $path2) == False)
{
echo $path1 . "<br>";
break;
}
}
echo "<br>";
}
?>

You need to use stripos() === false, as if they match it's going to return 0 which is == to false.
You have your parameters mixed, it should be stripos($path2, $path1).
You need to check all values in $paths2 until you find one it is in. You are saying it's not in any $paths2 after the first one you don't find it in. Set a flag of $flag = true; between the foreach() loops. Instead of echoing inside the second foreach, just set $flag == false if stripos($path2, $path1) !== false. After the second loop ends, but before the first, output if $flag == false.
ie
foreach ($paths1 as $path1)
{
$flag = true;
foreach ($paths2 as $path2)
{
if (stripos($path2, $path1) !== false)
{
$flag = false;
break;
}
}
if($flag)
echo $path1;
}
Note: didn't test it, but should work.

The arguments to stripos are backwards. Instead of:
if (stripos($path1, $path2) == False)
You want:
if (stripos($path2, $path1) === false)

Related

How to start a foreach loop with a specific value in PHP?

I need to start a for each loop at certain value, ex foreach($somedata as $data) Here I want to start doing some stuff only when the value of that data is "something"
I want to start doing something only after a specific value.
foreach($somedata as $data){
if($data == 'Something'){
//start processing, ignore all the before elements.
}
}
I tried break continue nothing seems to work as I wanted
For clarity, it's probably better to pre-process your array before looping over it. That way the logic inside your loop can purely focus on what it's supposed to do.
$arr = ['foo', 'something', 'bar'];
$toProcess = array_slice($arr, array_search('something', $arr));
foreach ($toProcess as $element) {
echo $element, PHP_EOL;
}
outputs
something
bar
How about using a indicator variable to achieve this.
$starter = 0;
foreach($somedata as $data){
if($data == 'Something'){
$starter = 1;
}
if(starter == 1){
//start processing, ignore all the before elements.
}
}
You'll need to keep a flag whether you have already encountered the desired value or not:
$skip = true;
foreach (... as $data) {
if ($data == 'something') {
$skip = false;
}
if ($skip) {
continue;
}
// do something
}
$skip = true;
foreach($somedata as $data){
if($data == 'Something'){
$skip = false;
}
if($skip) {
continue;
}
//start processing, ignore all before $skip == false.
}
If you want to process the values only from the moment you identify one value, then you can use a flag :
$flag = false;
foreach($somedata as $data){
if($flag OR $data == 'Something'){
$flag = true;
// processing some stuff
}
}
Once the flag is reset to true, whatever the current value is, the content of your if will be executed.

How do I remove values from an array?

This is the code I have written so far:
foreach ($link_body as $key => $unfinished_link)
{
#further Remove non ad links
if (stristr($unfinished_link, "inactive" OR "nofollow") === TRUE)
{
unset($link_body[$key]);
}
echo "<font color='#FFFFFF' size='16'>$unfinished_link</font><br>";
}
I'm not getting any error messages but I keep getting results that look like this:
/cars/" />
/cars/">
/cars/" class="inactive">(not what I wanted)
/cars/" class="inactive">(not what I wanted)
/cars/" class="inactive">(not what I wanted)
/cars/" rel="nofollow">(not what I wanted)
/cars/?layout=gallery" rel="nofollow">(not what I wanted)
/cars/2001-ford-escort-great-condition/1235588">(IS what I wanted)
Where am I messing up here guys? Thx
If you're trying to find a string inside that, maybe you indend to use stripos instead:
foreach ($link_body as $key => $unfinished_link) {
// further Remove non ad links
if(
stripos($unfinished_link, 'inactive') !== false ||
stripos($unfinished_link, 'nofollow') !== false
) {
unset($link_body[$key]);
} else {
echo "<font color='#FFFFFF' size='16'>$unfinished_link</font><br>";
// make sure your background is not white, or else your text will not be seen, at least on the white screen
}
}
If this is an HTML markup, consider using an HTML parser instead, DOMDocument in particular, and search for that attributes:
$rel = $node->getAttribute('rel'); // or
$class = $node->getAttribute('class');
You echo the variable $unfinished_link that it's different that $link_body[$key]. OK, the values are the same before you unset $link_body[$key] but it's like you are doing:
$a=1;
$b=1;
unset($a);
echo $b;
Of course, this code will echo the number one because I have unset a variable and echo other one. Also the condition of the If is incorrect.
Do not remove array's element inside foreach statement
Remember elements to delete in foreach, delete them after foreach:
$elements_to_delete = {};
foreach ($link_body as $key => $unfinished_link)
{
if(stristr($unfinished_link, "inactive" OR "nofollow") === TRUE) {
$elements_to_delete.push($key);
}
}
// removing elements after foreach complete
foreach($key in $elements_to_delete){
$link_body[$key];
}
Using array_filter :
function filterLink($link) {
return stripos($unfinished_link, 'inactive') === false &&
stripos($unfinished_link, 'nofollow') === false
}
$unfinished_link = array_filter($unfinished_link, "filterLInk")
To my knowledge, you cannot combine parameters in the way you try here :
if(stristr($unfinished_link, "inactive" OR "nofollow") === TRUE)
Instead, you can replace with
if(stristr($unfinished_link, "nofollow") === TRUE) || stristr($unfinished_link, "inactive") === TRUE)

Find if a value exist in a CSV file with PHP

This is my code to check if a row of my .csv file contains a specific name, but it does not work.
I think it has something to do with the if statement.
$file_handle = fopen("sources.csv", "r");
while (!feof($file_handle) ) {
$line_of_text = fgetcsv($file_handle, 1024);
if ($line_of_text[0] = 'paul') {
echo 'Found';
}
}
fclose($file_handle);
I am trying to check in sources.csv files, for the name 'Paul' .
I can't use a database like MySQL for technical reasons.
Since you haven't provided a sample of your file, am submitting the following as an alternative.
Do note that in your present code, you are assigning using a single equal sign = instead of comparing using == or ===, just saying as an FYI.
if ($line_of_text[0] = 'paul') should read as if ($line_of_text[0] == 'paul')
Assuming the following .csv format (will work even without the commas) and is case-sensitive, consult Footnotes regarding case-insensitive search.
Paul, Larry, Robert
Code:
<?php
$search = "Paul";
$lines = file('sources.csv');
$line_number = false;
while (list($key, $line) = each($lines) and !$line_number) {
$line_number = (strpos($line, $search) !== FALSE);
}
if($line_number){
echo "Results found for " .$search;
}
else{
echo "No results found for $search";
}
Footnotes:
For a case-insensitive search, use stripos()
$line_number = (stripos($line, $search) !== FALSE);
Row number found on...
To give you the row's number where it was found:
$line_number = (strpos($line, $search) !== FALSE) ? $count : $line_number;
or (case-insensitive)
$line_number = (stripos($line, $search) !== FALSE) ? $count : $line_number;
then just echo $line_number;
Your problem is this line:
if ($line_of_text[0] = 'paul') {
This will always be true because you are assigning the value paul to $line_of_text[0] with the assign operator =. What you want to do is check if the two are equal, so you need to use the equality operator, ==. The line of code should be:
if ($line_of_text[0] == 'paul') {
There is also the === equality operator in PHP which checks for the same value AND same type. (This is a particularly nasty feature of PHP when compared to compiled languages)
e.g. consider: `$foo = 5; $bar = "5";
if ($foo === $bar) // this will be false because foo is an int, and bar is a string
if ($foo == $bar) // this will be true
Don't be confused with the != comparison operator:
if ($foo != $bar) // foo is not equal to bar (note the single =)
Try using in_array instead of ==
if(in_array('paul', $line_of_text)) {
// FOUND
}

Checking if Any Item in Array is Found in a String

I know this question has been asked before but I haven't been able to get the provided solutions to work.
I'm trying to check if the words in an array match any of the words (or part of the words) in a provided string.
I currently have the following code, but it only works for the very first word in the array. The rest of them always return false.
"input" would be the "haystack" and "value" would be the "needle"
function check($array) {
global $input;
foreach ($array as $value) {
if (strpos($input, $value) !== false) {
// value is found
return true;
} else {
return false;
}
}
}
Example:
$input = "There are three";
if (check(array("one","two","three")) !== false) {
echo 'This is true!';
}
In the above, a string of "There is one" returns as true, but strings of "There are two" or "There are three" both return false.
If a solution that doesn't involve having to use regular expressions could be used, that would be great. Thanks!
The problem here is that check always returns after the first item in $array. If a match is found, it returns false, if not, it returns true. After that return statement, the function is done with and the rest of the items will not be checked.
function check($array) {
global $input;
foreach($array as $value) {
if(strpos($input, $value) !== false) {
return true;
}
}
return false;
}
The function above only returns true when a match is found, or false when it has gone through all the values in $array.
strpos(); is totally wrong here, you should simply try
if ($input == $value) {
// ...
}
and via
if ($input === $value) { // there are THREE of them: =
// ...
}
you can even check if the TYPE of the variable is the same (string, integer, ...)
a more professional solution would be
in_array();
which checks for the existance of the key or the value.
The problem here is that you're breaking out of the function w the return statement..so u always cut out after the first comparison.
you should use in_array() to compare the array values.
function check($array) {
global $input;
foreach ($array as $value) {
if (in_array($value,$input))
{
echo "Match found";
return true;
}
else
{
echo "Match not found";
return false;
}
}
}
You're returning on each iteration of $array, so it will only run once. You could use stristr or strstr to check if $value exists in $input.
Something like this:
function check($array) {
global $input;
foreach ($array as $value) {
if (stristr($input, $value)) {
return true;
}
}
return false;
}
This will then loop through each element of the array and return true if a match is found, if not, after finishing looping it will return false.
If you need to check if each individual item exists in $input you'd have to do something a little bit different, something like:
function check($array) {
global $input;
$returnArr = array();
foreach ($array as $value) {
$returnArr[$value] = (stristr($input, $value)) ? true : false;
}
return $returnArr;
}
echo '<pre>'; var_dump(check($array, $input)); echo '</pre>';
// outputs
array(3) {
["one"]=>
bool(false)
["two"]=>
bool(false)
["three"]=>
bool(true)
}
The reason your code doesnt work, is because you are looping through the array, but you are not saving the results you are getting, so only the last result "counts".
In the following code I passed the results to a variable called $output:
function check($array) {
global $input;
$output = false;
foreach ($array as $value) {
if (strpos($input, $value) != false) {
// value is found
$output = true;
}
}
return $output;
}
and you can use it like so:
$input = "There are two";
$arr = array("one","two","three");
if(check($arr)) echo 'this is true!';

How to check for one and only value?

I have an switch with a random variable name and a array which can contain the values left, right, up and down.
For example:
switch ($i) {
case 0:
$name='something1';
$array=array('north', 'south', 'west');
break;
case 1:
$name='something2';
$array=array('north', 'south');
case 2:
$name='something3';
$array=array('south');
}
How can I make a script that checks for example if the only value in the array is 'south'? In my script the output will be something3, and if I check for the value's north and south, the script would output something2?
Hope you understand me. Thanks!
I would do:
if((count($array) == 1) && ($array[0] == 'south')){
//code here
}
This will only work if the array has one element.
Ok, I think this is a pretty foolproof way of accomplishing this:
<?php
function checktangent($array,$tocheck){
$tocheck = explode(',', str_replace(' ', '', $tocheck));
if(count($tocheck) == count($array)){
$foundall = true;
foreach($tocheck as $value){
if(!in_array($value, $array))
$foundall = false;
}
return $foundall;
}
else
return false;
}
//Use like:
$array = array('north', 'south', 'west');
if(checktangent($array, 'north, south'))
echo 'found';
else
echo 'not found'
?>
You can compare arrays directly in PHP. Be careful though, because this also compares the order of the values.
var_dump(array(1, 2) == array(1, 2)); //true
var_dump(array(1, 2) == array(2, 1)); //false
If you can guarantee the same order, you could do something like this:
<?php
$directions = array('north', 'south');
switch($directions) {
case array('north'):
echo 'north';
break;
case array('south'):
echo 'south';
break;
case array('north', 'south'):
echo 'north south';
break;
}
?>
http://codepad.viper-7.com/TCoiDw
This should work if I understand what your looking for correctly
if (false == count(array_diff(array('north', 'south', 'west'), $array))) {
echo 'something1';
} else if (false == count(array_diff(array('north', 'south'), $array))) {
echo 'something2';
} else if (count($array) == 1 AND current($array) = 'south') {
echo 'something3';
}
I think an easier solution would be:
array_unique($array);
if (count($array) == 1 && in_array('south', $array))
// Only south exists.

Categories