I have imported a CSV to fill a multidimensional array. $arrCSV.
<?php
$foundOneMatchingRow = FALSE;
foreach ($arrCSV as $row) {
if (strpos($row['5'], $val) !== FALSE && strlen($row['5']) > 4) {
$foundOneMatchingRow = TRUE;
echo $row['6'];
}
}
?>
The above code outputs from the value of $val = $_GET['menu']; which is done buy the URL.
I would like to make a search if possible please based on words in $row['6'];.
There will be a search on the page which will pass the search to the URL.
Which would look something like http://example.com/search.php?val=dogs
So the code would look for ANYTHING that relates to dog in $row [6]
I hope I have been clear. Any gudiance would be more than welcome. I am testing everything now.
Thank you
if (strpos($row['6'], $val) !== FALSE) will evaluate to true if $row['6'] contains "dog" (if $val's value is "dog"). That is, will evaluate to true as well if the string in $row['6'] is "bulldog" or "whateverdogwhatever".
BTW, why do you need this condition: strlen($row['5']) > 4? (which I guess should be at least strlen($row['6']) > 4 if you search on $row['6']).
Something else: aren't you confusing strings and integers? Maybe if (strpos($row['6'], $val) !== FALSE) should be if (strpos($row[6], $val) !== FALSE)?
EDIT
I would suggest to define constants for your CSV columns, for readability.
What about for example:
define('CSV_ID', 5);
define('CSV_TEXT', 6);
//...
foreach ($arrCSV as $row) {
if (strpos($row[CSV_TEXT], $val) !== FALSE && strlen($row[CSV_ID]) > 4) {
//...
echo $row[CSV_TEXT];
}
}
Related
I have piece of code like this
foreach ($item->offers as $offer) {
foreach ($json as $akey => $article){
if ($article['A'] == $offer->OfferName){
echo $article['B'];
break;
} else {
echo $offer->OfferName
}
}
}
As you can see I want to loop through offers and see if they exist in json.
If they exist I want to get value B of article but if not I want just to echo offer name.
Unfortunately else statement return all of non matching iterations and I have no idea how to force it to return it only once.
E: I want return some value if none of iterations in second loop is matching given condition.
Maybe someone familiar with PHP know the solution.
Thanks.
Your else statement is defined within a second tier foreach so its normal to get the OfferName every single time - that's the logic you coded.
If I understand you correctly, you want the article value rendered only when each key matches your criteria, and the offer name if there's a key that doesn't match it. If this is the case then you can do this:
$match = 0;
$output = '';
foreach ( $item->offers as $offer ) {
foreach ( $json as $akey => $article){
if ($article['A'] == $offer->OfferName){
$output .= $article['B'].PHP_EOL;
// break; - this is pointless
} else {
$match = $offer->OfferName;
}
}
}
echo ( $match == 0 ? $output : $match);
I'm trying to check MD5 of some data with md5 some files, both of them are stored in one dimensional arrays. Say I have 4 files in the $files array with the same number of $datas, the following code prints "NO DIFFERENCE" 12 times instead of 4 times.
foreach($files as $file) {
foreach($datas as $data) {
if(md5($data) !== md5_file($file)) {
echo "NO DIFFERENCE";
}
}
}
How do I prevent duplicating a loop?
Update:
Both arrays $datas and $files contains equal number of values but the tricky part is the values in $files array starts from key number 2 (because I removed "." and ".." from scandir result) whereas in $datas array values start from key number 0.
the following code prints "NO DIFFERENCE" 12 times instead of 4 times.
The reason for that is you have a nested loop.
For each value in the $files array, your inner foreach will run once.
So say if you have 3 values in $files and 4 values in $datas, the loop will run as follows:
First value in $files iterated
Inner loop runs, and iterates through all 4 values in $datas
Second value in $files iterated
Inner loop runs, and iterates through all 4 values in $datas
Third value in $files iterated
Inner loop runs, and iterates through all 4 values in $datas
Try this with one loop like this :
foreach($datas as $key => $value) {
if(md5($value) !== md5_file($files[$key])) {
echo "NO DIFFERENCE";
}
}
Note: The loop work when you have same no of values for both arrays
If you want to compare md5(files) to the mfs5(datas) you can simply do this:
for ($i = 0; $i < sizeof($files); $i++){
if(md5($datas[$i]) !== md5_file($files[$i+2]))
echo "NO DIFFERENCE";
}
If you want to check if each file have one corresponding md5(datas) then you should use you double loop as you did.
First, are you sure that !== is the operator you want to use to say 'no difference' ?
If you are looking for equality, maybe you want to use ===
Second, md5(...) is time consuming, so extract the hash in a variable.
Third, if you mean equality, you can add a break in the inner loop to stop looping as soon as you find the equality.
foreach($files as $file) {
$md5File = md5_file($file); // extract in a variable
foreach($datas as $data) {
if(md5($data) === $md5File) { // === instead of !==
echo "NO DIFFERENCE";
break; // break as soon as possible
}
}
}
You could use a callback function. But then you should be clear about how exactly you will describe an algorithm of your problem.
The following sample shows how to maybe achieve it. But it assumes that the arrays are in the same order and that you don't want to cross-compare everything. Also array_udiff may not be the best approach for it.
function compare_by_md5($data, $file) {
if( md5($data) === md5_file($file)) {
echo "NO DIFFERENCE";
}
}
array_udiff($datas, $files, 'compare_by_md5');
Sample is shown here: http://codepad.org/lYOyCuXA
If you simply want to detect if there is a difference:
$dataHashes = array();
foreach($datas as $data) {
$dataHashes[md5($data)] = true;
}
$different = false;
foreach($files as $file) {
if(!isset($dataHashes[md5_file($file)])) {
$different = true;
break;
}
}
var_dump($different);
If you want to know which files are different, then:
$dataHashes = array();
foreach($datas as $data) {
$dataHashes[md5($data)] = true;
}
foreach($files as $file) {
if(!isset($dataHashes[md5_file($file)])) {
echo $file, 'is different', PHP_EOL;
}
}
i have this array, and all i want it to do is cycle through and just remove certain elements that appear in the if, however whenever i output the array it always just shows
array(0) { }
instead of
["addon_h_id"]=> string(1) "1"
Here is the code which cycles through it, if i remove this code then the array displays as normal
foreach ($new_shopping_array as $columnName => $columnData) {
if($columnName == "s_list_id" || "user_id"){
unset($new_shopping_array[$columnName]);
}
}
Thanks for any and all help
Operator precedence: You're doing $columnName = "s_list_id", then ORing the result of that against "user_id"
if($columnName == "s_list_id" || $columnName == "user_id"){
The problem is your if statement:
if($columnName == "s_list_id" || "user_id")
The string "user_id" will evaluate to true so all values will be removed.
You probably want something like:
if (in_array($columnName, array('s_list_id', 'user_id')))
How about:
$new_array = array();
foreach ($new_shopping_array as $columnName => $columnData)
{
if ($columnName != "s_list_id" && $columnName != "user_id")
{
$new_array[$columnName] = $columnData;
}
}
$new_array contains the data you need.
If you prefer your solution you will need to alter the conditional a bit like so:
foreach ($new_shopping_array as $columnName => $columnData)
{
if ($columnName == "s_list_id" || $columnName == "user_id")
{
unset($new_shopping_array[$columnName]);
}
}
The way it was written it told php that if $columnName is equal to s_list_id OR "user_id". The condition was not in the columnName and "user_id" validates as TRUE (since it has something in there). So your conditional was always TRUE thus removing everything from the original array.
HTH
$list = array(
[0]=> array(
[name]=>'James'
[group]=>''
)
[1]=> array(
[name]=>'Bobby'
[group]=>''
)
)
I am looking to update the item 'group' where the name is 'Bobby'. I am looking for a solution with the two following formats. Thank you in advance for your replies. Cheers. Marc.
array_push($list, ???)
and
$list[] ??? = someting
As far as I know, there's no way updating your array with one of the given syntax.
The only similar thing I can come on is looping over the array using array_walk ... http://www.php.net/manual/en/function.array-walk.php
Example:
array_walk($list, function($val, $key) use(&$list){
if ($val['name'] == 'Bobby') {
// If you'd use $val['group'] here you'd just editing a copy :)
$list[$key]['group'] = "someting";
}
});
EDIT: Example is using anonymous functions which is only possible since PHP 5.3. Documentation offers also ways working with older PHP-versions.
This code may help you:
$listSize = count($list);
for( $i = 0; $i < $listSize; ++$i ) {
if( $list[$i]['name'] == 'Bobby' ) {
$list[$i]['group'] = 'Hai';
}
}
array_push() doesn't really relate to updating a value, it only adds another value to an array.
You cannot have a solution that will fit both formats. The implicit array push $var[] is a syntactic construct, and you cannot invent new ones - certainly not in PHP, and not most (all?) other languages either.
Aside from that, what you are doing is not pushing an item on to the array. For one thing, pushing items implies an indexed array (yours is associative), and for another pushing implies adding a key to the array (the key you want to update already exists).
You can write a function to do it, something like this:
function array_update(&$array, $newData, $where = array(), $strict = FALSE) {
// Check input vars are arrays
if (!is_array($array) || !is_array($newData) || !is_array($where)) return FALSE;
$updated = 0;
foreach ($array as &$item) { // Loop main array
foreach ($where as $key => $val) { // Loop condition array and compare with current item
if (!isset($item[$key]) || (!$strict && $item[$key] != $val) || ($strict && $item[$key] !== $val)) {
continue 2; // if item is not a match, skip to the next one
}
}
// If we get this far, item should be updated
$item = array_merge($item, $newData);
$updated++;
}
return $updated;
}
// Usage
$newData = array(
'group' => '???'
);
$where = array(
'name' => 'Bobby'
);
array_update($list, $newData, $where);
// Input $array and $newData array are required, $where array can be omitted to
// update all items in $array. Supply TRUE to the forth argument to force strict
// typed comparisons when looking for item(s) to update. Multiple keys can be
// supplied in $where to match more than one condition.
// Returns the number of items in the input array that were modified, or FALSE on error.
i want to do the foreach only if the content of myformdata[languages1][] is not empty (include zero)
I already try:
foreach((!empty($form['languages1']) as $val){
and
if (!empty($form['languages1'][])) {
foreach($form['languages1'] as $val){
//do stuff
}
i don't have any success. At the moment with the code below the loop is made when the input of myformdata[languages1][] is 0
foreach
foreach($form['languages1'] as $val){
//do stuff
}
thanks
foreach ( $form['languages1'] as $val )
{
// If the value is empty, skip to the next.
if ( empty($val) )
continue;
}
Reference: http://ca.php.net/continue
You're dealing with type coersion
You probably want something like
if(!empty($form['languages1']) && $form['languages1'] !== 0)
So that PHP will match 0 as a number, and not as false.