I'm working on a php function that will compare the components of two arrays. Each value in the arrays are only one english word long. No spaces. No characters.
Array #1: a list of the most commonly used words in the english
language. $common_words_array
Array #2: a user-generated sentence, converted to lowercase, stripped
of punctuation, and exploded() using the space (" ") as a delimiter.
$study_array
There's also a $com_study array, which is used in this case to keep
track of the order of commonly used words which get replaced in the
$study_array by a "_" character.
Using nested for loops, what SHOULD happen is that the script should compare each value in Array #2 to each value in Array #1. When it finds a match (aka. a commonly used english word), it will do some other magic that's irrelevant to the current problem.
As of right now, PHP doesn't recognize when two array string values are equivalent. I'm adding in the code to the problematic function here for reference. I've added in a lot of unnecessary echo commands in order to localize the problem to the if statement.
Can anybody see something that I've missed? The same algorithm worked perfectly in Python.
function create_question($study_array, $com_study, $common_words_array)
{
for ($study=0; $study<count($study_array); $study++)
{
echo count($study_array)." total in study_array<br>";
echo "study is ".$study."<br>";
for ($common=0; $common<count($common_words_array); $common++)
{
echo count($common_words_array)." total in common_words_array<br>";
echo "common is ".$common."<br>";
echo "-----<br>";
echo $study_array[$study]." is the study list word<br>";
echo $common_words_array[$common]." is the common word<br>";
echo "-----<br>";
// The issue happens right here.
if ($study_array[$study] == $common_words_array[$common])
{
array_push($com_study, $study_array[$study]);
$study_array[$study] = "_";
print_r($com_study);
print_r($study_array);
}
}
}
$create_question_return_array = array();
$create_question_return_array[0] = $study_array;
$create_question_return_array[1] = $com_study;
return $create_question_return_array;
}
EDIT: At the suggestion of you amazing coders, I've updated the if statement to be much more simple for purposes of debugging. See below. Still having the same issue of not activating the if statement.
if (strcmp($study_array[$study],$common_words_array[$common])==0)
{
echo "match found";
//array_push($com_study, $study_array[$study]);
//$study_array[$study] = "_";
//print_r($com_study);
//print_r($study_array);
}
EDIT: At bansi's request, here's the main interface snippet where I'm calling the function.
$testarray = array();
$string = "This is a string";
$testarray = create_study_string_array($string);
$testarray = create_question($testarray, $matching, $common_words_array);
As for the result, I'm just getting a blank screen. I would expect to have the simplified echo statement output "match found" to the screen, but that's not happening.
(EDIT) make sure your that your splitting function removes excess whitespace (e.g. preg_split("\\s+", $input)) and that the input is normalized properly (lowercase'd, special chars stripped out, etc.).
On mobile and can't seem to copy text. You forgot a dollar sign when accessing the study array in your push command.
change
array_push($com_study, $study_array[study]);
to
array_push($com_study, $study_array[$study]);
// You missed a $ ^ here
Edit:
The following code outputs 3 'match found'. i don't know the values of $common_words_array and $matching, so i used some arbitrary values, also instead of using function create_study_string_array i just used explode. still confused, can't figure out what exactly you are trying to achieve.
<?php
$testarray = array ();
$string = "this is a string";
$testarray = explode ( ' ', $string );
$common_words_array = array (
'is',
'a',
'this'
);
$matching = array (
'a',
'and',
'this'
);
$testarray = create_question ( $testarray, $matching, $common_words_array );
function create_question($study_array, $com_study, $common_words_array) {
echo count ( $study_array ) . " total in study_array<br>";
echo count ( $common_words_array ) . " total in common_words_array<br>";
for($study = 0; $study < count ( $study_array ); $study ++) {
// echo "study is " . $study . "<br>";
for($common = 0; $common < count ( $common_words_array ); $common ++) {
// The issue happens right here.
if (strcmp ( $study_array [$study], $common_words_array [$common] ) == 0) {
echo "match found";
}
}
}
$create_question_return_array = array ();
$create_question_return_array [0] = $study_array;
$create_question_return_array [1] = $com_study;
return $create_question_return_array;
}
?>
Output:
4 total in study_array
3 total in common_words_array
match foundmatch foundmatch found
Use === instead of ==
if ($study_array[$study] === $common_words_array[$common])
OR even better use strcmp
if (strcmp($study_array[$study],$common_words_array[$common])==0)
Use built-in functions wherever possible to avoid unnecessary code and typos. Also, providing sample inputs would be helpful too.
$study_array = array("a", "cat", "sat", "on","the","mat");
$common_words_array = array('the','a');
$matching_words = array();
foreach($study_array as $study_word_index=>$study_word){
if(in_array($study_word, $common_words_array)){
$matching_words[] = $study_word;
$study_array[$study_word_index] = "_";
//do something with matching words
}
}
print_r($study_array);
print_r($matching_words);
Related
I would like to ask if it is possible to cut a word like
"Keyboard" in multiple strings, in PHP?
I want the string to be cut whenever a / is in it.
Example:
String: "Key/boa/rd"
Now I want that the cut result look like this:
String1: "Key"
String2: "boa"
String3: "rd"
You can use the PHP explode function. So, if your string was "Key/boa/rd", you would do:
explode('/', 'Key/boa/rd');
and get:
[
"Key",
"boa",
"rd",
]
It's unclear from your question, but if you don't want an array (and instead would like variables) you can use array destructuring like so:
[$firstPart, $secondPart, $thirdPart] = explode('/', 'Key/boa/rd');
However, if the string only had one / then that approach could lead to an exception being thrown.
The answer by Nathaniel assumes that your original string contains / characters. It is possible that you only used those in your example and you want to split the string into equal-length substrings. The function for that is str_split and it looks like:
$substrings = str_split($original, 3);
That will split the string $original into an array of strings, each of length 3 (except the very last one if it doesn't divide equally).
You can travel through the line character by character, checking for your delimeter.
<?php
$str = "Key/boa/rd";
$i = $j = 0;
while(true)
{
if(isset($str[$i])) {
$char = $str[$i++];
} else {
break;
}
if($char === '/') {
$j++;
} else {
if(!isset($result[$j])) {
$result[$j] = $char;
} else {
$result[$j] .= $char;
}
}
}
var_export($result);
Output:
array (
0 => 'Key',
1 => 'boa',
2 => 'rd',
)
However explode, preg_split or strtok are probably the goto Php functions when wanting to split strings.
This question already has answers here:
How can I combine two strings together in PHP?
(19 answers)
Closed 5 years ago.
Apologies in advance though I've tried and failed several different things and obviously I'm not a php pro just yet.
I'm looking for a way to tidy up my code here, I'm pretty certain I don't need to continually type "echo" for each line but can't work out how to combine my code to achieve the same result, any ideas?
<?php
$values = get_field('bothscoreno');
$url = "$values";
$arr = str_split("$url, PHP_URL_QUERY");
if ($url) {
echo $arr[11];
echo $arr[12];
echo $arr[13];
echo $arr[14];
echo $arr[15];
echo $arr[16];
} else {
echo 'No';
}
?>
Thanks in advance.
The code you posted probably has bugs, because the way it's written, it looks like it's intended to do something different from what it is actually going to do.
str_split() will take a string and output an array of single characters. It looks like you're trying to pass it two parameters, but enclosing them in quotes means it's actually just a single string.
Thus, if $url is equal to abc, your str_split() call will output an array of a, b, c, ,, , P, H, P, _, U, R, L, _ ... etc.
I don't think that's what you intended.
However, if it is what you intended, then you are splitting the string, only to re-join some of the characters back together again with echo. You can therefore can simplify the whole thing as follows:
$url = get_field('bothscoreno');
if ($url) {
echo substr($url, 11, 6);
} else {
echo "No.";
}
If I'm right and this isn't what you actually want to do, then I suggest either editing the question to clarify or asking a whole new one.
use for loop and start index from 14 to echo your result
$values = get_field('bothscoreno');
$url = $values;
$arr = str_split("$url, PHP_URL_QUERY");
$string = '';
if ($url) {
for($i = 11;$i <= 16;$i++){
$string .= $arr[$i];
}
} else {
$string = 'No';
}
echo $string;
Use the point as concatenation operator
echo $arr[11].$arr[12]
in PHP you're able to use a . as concatenation operator.
See the code below:
<?php
$values = get_field('bothscoreno');
$url = "$values";
$arr = str_split("$url, PHP_URL_QUERY");
if ($url) {
echo $arr[11].
$arr[12].
$arr[13].
$arr[14].
$arr[15].
$arr[16];
} else {
echo 'No';
}
Hope this helps!
Use array_slice
<?php
$values = get_field('bothscoreno');
$url = "$values";
$arr = str_split("$url, PHP_URL_QUERY");
if ($url) {
$subArr = array_slice($arr, 11, 6);
print_r($subArr);
// Or...
foreach ($subArr as $val) {
echo $val;
}
} else {
echo 'No';
}
?>
I've been searching and searching and can't find anything that works, but this is what I want to do.
This code:
try{
$timeout = 2;
$scraper = new udptscraper($timeout);
$ret = $scraper->scrape('udp://tracker.openbittorrent.com:80',array('0D7EA7F06E07F56780D733F18F46DDBB826DCB65'));
print_r($ret);
}catch(ScraperException $e){
echo('Error: ' . $e->getMessage() . "<br />\n");
echo('Connection error: ' . ($e->isConnectionError() ? 'yes' : 'no') . "<br />\n");
}
Outputs this:
Array ( [0D7EA7F06E07F56780D733F18F46DDBB826DCB65] => Array ( [seeders] => 148 [completed] => 10 [leechers] => 20 [infohash] => 0D7EA7F06E07F56780D733F18F46DDBB826DCB65 ) )
And I want that seeder count into a string such as $seeds. How would I go about doing this?
Something like this?
$seeds = $ret['0D7EA7F06E07F56780D733F18F46DDBB826DCB65']['seeders'];
you can user strval() to convert a number to a string.
$string = strval($number);
or you can cast it into a string:
$string = (string)$number;
in your context that would be:
$string = strval($ret['0D7EA7F06E07F56780D733F18F46DDBB826DCB65']['seeders']);
However that odd string is also the first index of the array so you could also do it like this:
$string = strval($ret[0]['seeders']);
or if you want ot use only indexes ('seeders' is also the first index of the second array):
$string = strval($ret[0][0]);
if you just want the number then it's easy too:
$num = $ret[0][0];
It's not clear if you're looking to assign the array value(s?) as a separate variable(s?) or just to cast it into a string. Here's a nice way to accomplish all the above options, by assigning each array key as a separate variable with the matching array value:
$ret_vars = array_pop($ret);
foreach ($ret_vars as $variable_name=>$variable_value) :
${$variable_name} = (string)$variable_value;
endforeach;
In your original example, this would end up populating $seeders, $completed, $leechers and $infohash with their matching string values. Of course, make sure these variable names are not used/needed elsewhere in the code. If that's the case, simply add some sort of unique prefix to the ${} construct, like ${'ret_'.$variable_name}
I have the following code that is not returning as I expected. I was hoping the final result would be a string:
$organizers = array_unique($organizers); // this returns correctly
$organizers = implode(', ', $organizers); // this returns nothing
var_dump($organizers); // no data appears here
exit;
The array_unique() function is returning data correctly and I can see the array it returns. To start, the $organizers array is a simple 1-D array of strings that all have small lengths under 20 chars. I think the issue might be that $organizers is more than 10,000 indices long. Are there limitations on the length of an array that can be imploded? Are there work-arounds for that? I cannot find anything in the manual, but I have tested this code thoroughly and I believe the error must be on implode().
I dont' know if there is a limitation, but what comes to my mind is taht you are also transforming an array into a string. This shouldn't be the problem in PHP, but try calling it a different variable for the result of implode?
$organizers = array_unique($organizers); // this returns correctly
$organizers_string = implode(', ', $organizers); // this returns nothing
// This gives it a different space
Edit: And if for some reason implode() is still problematic.
$organizers = array_unique($organizers);
$neworganizers = "";
for($i = 0; $i < sizeof($organizers); $i++)
{
$neworganizers .= $organizers[$i];
if($i != sizeof($organizers) - 1)
{
$neworganizers .= ", ";
}
}
//$neworganizers is now the equivalent of what .implode() should return when called on $organizers
$organizers = array();
$organizers[0] = "value1";
$organizers[1] = "value2";
$organizers[2] = "value3";
$organizers[3] = "value3";
$organizers = array_unique($organizers); // strips out last index
$organizers = implode(', ', $organizers); // returns string of "value1, value2, value3"
echo $organizers;
This seemed to work on writecodeline.com/php/
I've also experienced issues with older php builds when I've tried to explode/implode by a string with special characters in it and they were encapsulated by single quotes. I know it sounds crazy, but the double quotes might be necessary on some servers.
Reference: personal experience doing work on older production servers.
I'd hate to think I'm stating the obvious, but doesn't implode only take a string as an argument? Maybe it should be something more like this...
$organizers = array_unique($organizers);
//I'm guessing what you wanted was an array of arrays?
$neworganizers = array();
for($i = 0; $i < sizeof($organizers); $i++)
{
$neworganizers[$i] = implode(", ", $organizers);
}
print_r($neworganizers);
I've seen a million of these threads here already, and read through every single one. That, plus some serious Googling.
UPDATE: I am rewriting this post to include complete code and explanation, so everyone understands what is going on and what I am trying to do.
I am developing using CodeIgniter, so some syntax may look weird if you are not familiar with it.
I have an link bar with letters A-Z. The idea is to find only "active" letters that have content in a particular column (mysql LIKE $letter%). With this information I would be able to "dim" certain "empty" letters if there are any, using CSS.
This function here queries mysql and gets each unique first letter of entries in a column. The result should be anywhere from 0 to 26 matches/array items.
//From am_model.php
function getFirstLetter($domainId)
{
$q = $this->db->query("SELECT DISTINCT LEFT(alias_name, 1)
AS letter
FROM am_aliases
WHERE domain_id = '" . $domainId . "'
ORDER BY alias_name;");
if($q->num_rows > 0):
foreach($q->result() as $row)
{
$result[] = $row;
}
//print_r($result); <-- prints out correct result.
return $result;
endif;
}
After that, I call this function from a controller:
$foundLetters = $this->am_model->getFirstLetter($domainId);
then define an $alphabet array.
$alphabet = range('a','z');
foreach($alphabet as $letter)
{
if(in_array($letter, $foundLetters, TRUE)):
echo $letter . ' found<br />';
else:
echo $letter . ' not found<br />';
endif;
}
Nothing complicated. All I have to do is check if a single character in a loop matches my alphabet array.
As Col. Shrapnel suggested below, I did some debugging, and dump() of letters from $alphabet and $foundLetters arrays produce different results, so I guess it does point
to possible encoding issues, which I am trying to figure out now...
Does anyone have any idea what the hell is going on here??
function dump(&$str) {
$i=0;
while (isset($str[$i])) echo strtoupper(dechex(ord($str[$i++])));
}
Here is the result from dump():
a: $alphabet->61 613C6272202F3E<-$foundLetters
b: $alphabet->62 613C6272202F3E<-$foundLetters
c: $alphabet->63 683C6272202F3E<-$foundLetters
d: $alphabet->64 613C6272202F3E<-$foundLetters
and these:
print_r($alphabet); // all 26 letters
Array (
[0] => a
[1] => b
[2] => c
...
[23] => x
[24] => y
[25] => z
)
print_r($foundLetters); // dynamic array.
Array (
[0] => b
[1] => s
)
got your letters from the file, eh? :)
use var_dump instead or print_r and trim in comparison :)
Edit
Use this code to see what is going on
foreach ($alphabet as $letter) {
foreach ($empty_letters as $empty) {
dump($letter);
echo " ";
dump($empty);
echo "<br>";
if ($letter == $empty) {
echo "$letter was found in \$empty_letters<br>\n";
break;
}
}
}
function dump(&$str) {
$i=0;
while (isset($str[$i])) echo strtoupper(dechex(ord($str[$i++])));
}
Works for me
The only thing in your sample that is strange is the : that comes after the foreach - followed by curly braces will cause a syntax error. Is that the problem, or does your program just not output anything?
I got the expected results as well. But I think your example array is different from what you are actually passing through. Give this a try...
foreach(array_values($alphabet) as $letter){
echo $letter . '<br />'; // Correctly prints out every letter from $alphabet.
if(in_array($letter, $emptyLetters)) { // $strict is set
// do something
echo 'found';
}
}