I've problem with strpos(), is not returning properly position, but always false.
class generate
{
function test()
{
$array1 = file_get_contents('file.csv'); //get content of file
$array1 = explode(PHP_EOL, $array1); //each row in table
foreach($array1 as $key => $value)
{
$array2 = preg_split("/[\t]/", $value); //to split each row into separate arrays fields
}
foreach($array2 as $array3)
{
$array3[2] = '[TRIGGER] ...';
var_dump(strpos($array3[2], 'TRIGGER'));
}
}
}
$test = new generate();
$test->test();
In place of three dots in $array3[2] there is a different content. I've check and content of $array3[2] is ok, but it still don't want to find my needle in string. The $array takes data from csv file using file_get_contents();. Any advices?
Thanks
Ok I will answer myself, the PHP file was coded in UTF-8, when I change to UTF-8 CSV file, everything start to work properly.
Thanks! :)
Related
I am uploading a CSV file/report with 10 columns but at the end of the CSV file there are a few lines that just give details about the report like
Generated By: XXX
Company Name
Report Run # 2019-03-14
When I load the array, the keys are just numeric (from 0-9) but I wanted to make it be an associative array based on the column headers. Unfortunately this will not work for the last few lines since the array dimensions are different (1 vs 10)
Here is my code:
$csv = array_map('str_getcsv', file($_FILES['file']['tmp_name']));
array_walk($csv, function(&$a) use ($csv) {
if(count($csv[0]) != count($a)) {
$a = null; // Remove the array
} else {
$a = array_combine($csv[0], $a);
}
});
array_shift($csv); # remove column header
When I do $a = null; it sort of 'deletes it' by replacing it with NULL. When I iterate through the arrays I do if(is_null($row)) continue; to ignore the NULL element. Is there a way to actually delete the array?
I think it's more straightforward without array_walk. array_walk is just going to apply the function to every member of the array. Setting it to null doesn't mean it's gone, it just has a null value as you've seen. If you really want it gone, you need to unset it. Just refer to $csv by key and unset the ones you don't want.
$keys = array_shift($csv);
$expected_count = count($keys);
foreach ($csv as $index => $values) {
if (count($values) == $expected_count) {
$csv[$index] = array_combine($keys, $values);
} else {
unset($csv[$index]);
}
}
Array_filter($csv); afterwards will remove all null/false/0 from your array.
So it may be smarter to write a custom function to remove null only.
I have a key value pair string that I would like to convert to a functional array. So that I can reference the values using their key. Right now I have this:
$Array = "'Type'=>'Honda', 'Color'=>'Red'";
$MyArray = array($Array);
This is not bringing back a functional key/value array. My key value pairs are in a variable string which means the => is part of the string and i think this is where my problem is. Any help would be appreciated. All i am trying to do is convert the string to a functional key/value pair where I can grab the values using the key. My data is in a string so please don't reply with the answer "take them out of the string." I am aware that this will work:
$MyArray = array('Type'=>'Honda', 'Color'=>'Red');
But my probem is that the the data is already in the form of a string. Thank you for any help.
There is no direct way to do this. As such, you'll need to write a custom function to build the keys and values for each element.
An example specification for the custom function:
Use explode() to split each element based on the comma.
Iterate over the result and:
explode() on =>
Remove unnecessary characters, i.e. single quotes
Store the first element as the key and the second element as the value
Return the array.
Note: if your strings contain delimiters this will be more challenging.
You do need to "take them out of the string", as you say. But you don't have to do it manually. The other answer uses explode; that's a fine method. I'll show you another - what I think is the easiest way is to use preg_match_all() (documentation), like this:
$string = "'Type'=>'Honda', 'Color'=>'Red'";
$array = array();
preg_match_all("/'(.+?)'=>'(.+?)'/", $string, $matches);
foreach ($matches[1] as $i => $key) {
$array[$key] = $matches[2][$i];
}
var_dump($array);
You need to parse the string and extract the data:
$string = "'Type'=>'Honda', 'Color'=>'Red'";
$elements = explode(",",$string);
$keyValuePairs = array();
foreach($elements as $element){
$keyValuePairs[] = explode("=>",$element);
}
var_dump($keyValuePairs);
Now you can create your on array using the $keyValuePairs array.
Here is an example of one way you can do it -
$Array = "'Type'=>'Honda', 'Color'=>'Red'";
$realArray = explode(',',$Array); // get the items that will be in the new array
$newArray = array();
foreach($realArray as $value) {
$arrayBit = explode('=>', $value); // split each item
$key = str_replace('\'', '', $arrayBit[0]); // clean up
$newValue = str_replace('\'', '', $arrayBit[1]); // clean up
$newArray[$key] = $newValue; // place the new item in the new array
}
print_r($newArray); // just to see the new array
echo $newArray['Type']; // calls out one element
This could be placed into a function that could be extended so each item gets cleaned up properly (instead of the brute force method shown here), but demonstrates the basics.
I've taken a look around but cant seem to find anything that does as needed.
Lets say I have 2 arrays in a function, however they are completely dynamic. So each time this function is run, the arrays are created based on a page that has been submitted.
I need to some how match these arrays and look for any phrase/words that appear in both.
Example: (with only a single element in each array)
Array 1: "This is some sample text that will display on the web"
Array 2: "You could always use some sample text for testing"
So in that example, the 2 arrays have a phrase that appears exactly the same in each: "Sample Text"
So seeing as these arrays are always dynamic I am unable to do anything like Regex because I will never know what words will be in the arrays.
You could find all words in an array of strings like this:
function find_words(array $arr)
{
return array_reduce($arr, function(&$result, $item) {
if (($words = str_word_count($item, 1))) {
return array_merge($result, $words);
}
}, array());
}
To use it, you run the end results through array_intersect:
$a = array('This is some sample text that', 'will display on the web');
$b = array('You could always use some sample text for testing');
$similar = array_intersect(find_words($a), find_words($b));
// ["some", "sample", "text"]
Array_intersect() should do this for you:
http://www.php.net/manual/en/function.array-intersect.php
*array_intersect() returns an array containing all the values of array1 that are present in all the arguments. Note that keys are preserved.*
maybe something like this:
foreach($arr as $v) {
$pos = strpos($v, "sample text");
if($pos !== false) {
// success
}
}
here is the manual:
http://de3.php.net/manual/de/function.strpos.php
Explode the two strings by spaces, and it is a simple case of comparing arrays.
What i am trying to do is really but i am going into a lot of detail to make sure it is easily understandable.
I have a array that has a few strings in it. I then have another that has few other short strings in it usually one or two words.
I need it so that if my app finds one of the string words in the second array, in one of the first arrays string it will proceed to the next action.
So for example if one of the strings in the first array is "This is PHP Code" and then one of the strings in the second is "PHP" Then it finds a match it proceeds to the next action. I can do this using this code:
for ( $i = 0; $i < count($Array); $i++) {
$Arrays = strpos($Array[$i],$SecondArray[$i]);
if ($Arrays === false) {
echo 'Not Found Array String';
}
else {
echo 'Found Array String';
However this only compares the First Array object at the current index in the loop with the Second Array objects current index in the loop.
I need it to compare all the values in the array, so that it searches every value in the first array for the First Value in the second array, then every value in the First array for the Second value in the second array and so on.
I think i have to do two loops? I tried this but had problems with the array only returning the first value.
If anyone could help it would be appreciated!
Ill mark the correct answer and + 1 any helpful comments!
Thanks!
Maybe the following is a solution:
// loop through array1
foreach($array1 as $line) {
// check if the word is found
$word_found = false;
// explode on every word
$words = explode(" ", $line);
// loop through every word
foreach($words as $word) {
if(in_array($word, $array2)) {
$word_found = true;
break;
}
}
// if the word is found do something
if($word_found) {
echo "There is a match found.";
} else {
echo "No match found."
}
}
Should give you the result you want. I'm absolute sure there is a more efficient way to do this.. but thats for you 2 find out i quess.. good luck
You can first normalize your data and then use PHP's build in array functions to get the intersection between two arrays.
First of all convert each array with those multiple string with multiple words in there into an array only containing all words.
A helpful function to get all words from a string can be str_word_count.
Then compare those two "all words" arrays with each other using array_intersect.
Something like this:
$words1 = array_unique(str_word_count(implode(' ', $Array), 1));
$words2 = array_unique(str_word_count(implode(' ', $SecondArray), 1));
$intersection = array_intersect($words1, $words2);
if(count($intersection))
{
# there is a match!
}
function findUnit($packaging_units, $packaging)
{
foreach ($packaging_units as $packaging_unit) {
if (str_contains(strtoupper($packaging[3]), $packaging_unit)) {
return $packaging_unit;
}
}
}
Here First parameter is array and second one is variable to find
suppose I have an array of names, what I want is that I want to search this particular array against the string or regular expression and then store the found matches in another array. Is this possible ? if yes then please can your give me hint ? I am new to programming.
To offer yet another solution, I would recommend using PHP's internal array_filter to perform the search.
function applyFilter($element){
// test the element and see if it's a match to
// what you're looking for
}
$matches = array_filter($myArray,'applyFilter');
As of PHP 5.3, you can use an anonymous function (same code as above, just declared differently):
$matches = array_filter($myArray, function($element) {
// test the element and see if it's a match to
// what you're looking for
});
what you would need to di is map the array with a callback like so:
array_filter($myarray,"CheckMatches");
function CheckMatches($key,$val)
{
if(preg_match("...",$val,$match))
{
return $match[2];
}
}
This will run the callback for every element in the array!
Updated to array_filter
well in this case you would probably do something along the lines of a foreach loop to iterate through the array to find what you are looking for.
foreach ($array as $value) {
if ($searching_for === $value) {/* You've found what you were looking for, good job! */}
}
If you wish to use a PHP built in method, you can use in_array
$array = array("1", "2", "3");
if (in_array("2", $array)) echo 'Found ya!';
1) Store the strings in array1
2) array2 against you want to match
3) array3 in which you store the matches
$array1 = array("1","6","3");
$array2 = array("1","2","3","4","5","6","7");
foreach($array1 as $key=>$value){
if(in_array($value,$array2))
$array3[] = $value;
}
echo '<pre>';
print_r($array3);
echo '</pre>';