How to Compare related strings? - php

so i have a problem with my program where i search a name in an array called ArrName then display handsome or beautiful if he/she exist in the array but if the name is not in the array then the program will display the related strings if the string that i searched does not exist inside the array. i have a hard time solving this please help.Here is a my example.
SAMPLE OUTPUT #1:
Names: Bob, John, Charlie, Bravo, Alpha, Raymond, Kenneth, Rose, Rosel, James
Searching for: bob.
Result: Bob exist, Bob is handsome
SAMPLE OUTPUT#2:
Names: Bob, John, Charlie, Bravo, Alpha, Raymond, Kenneth, Rose, Rosel, James
Searching for: roger.
Result: Roger not found. did you mean:
Rose?
Rosel?
here is my code so far:
<html>
<body>
<?php
$arrNumbers = array('jonel','jon','john','rosel','rosil','rose','ramon','ramin','ramoon','kenneth','keneth','kennet','joy','juy');
$arrboys = array('jonel','jon','john','ramon','ramin','ramoon','kenneth','keneth','kennet');
$arrgirls = array('rosel','rosil','rose','joy','juy');
$strsearch = 'rosel';
$count = 0;
$badd = 0;
$gadd = 0;
foreach($arrNumbers as $value)// checks if name exists
{
if($value == $strsearch)
{
$count = $count + 1;
}
else
{
$count = $count + 0;
}
}
if($count > 0)// if name exists, checks if the name is from a boy or a girl
{
//boys
foreach($arrboys as $value)// checks if the name is from the boys
{
if($value == $strsearch)
{
$badd = $badd + 1;
}
else
{
$badd = $badd + 0;
}
}
if($badd > 0)
{
echo $strsearch.' is handsome';
}
// girls
foreach($arrgirls as $value)// checks if the name is from the girls
{
if($value == $strsearch)
{
$gadd = $gadd + 1;
}
else
{
$gadd = $gadd + 0;
}
}
if($gadd > 0)
{
echo $strsearch.' is beautiful';
}
}
else// if the name does not exists
{
// this is the part where i dont know what to do.
// this part suppose to display all the names related to the name that is
// being searched.
echo 'did you mean';
}
?>
</body>

Why are you checking occurrence in $arrNumbers array as $arrboys and $arrgirls are substring of $arrNumbers.
Use below code
<?php
$arrNumbers = array('jonel','jon','john','rosel','rosil','rose','ramon','ramin','ramoon','kenneth','keneth','kennet','joy','juy');
$arrboys = array('jonel','jon','john','ramon','ramin','ramoon','kenneth','keneth','kennet');
$arrgirls = array('rosel','rosil','rose','joy','juy');
$strsearch = 'rosel';
$flag = '';
for($i=0;$i<sizeof($arrboys);$i++)
{
//echo $arrboys[$i].' ';
if($strsearch == $arrboys[$i]);
$flag = 'boy';
}
for($i=0;$i<sizeof($arrgirls);$i++)
{
//echo $arrboys[$i].' ';
if($strsearch == $arrgirls[$i]);
$flag = 'girl';
}
if($flag == 'boy')
{
echo $strsearch.' exist, '. $strsearch.' is handsome';
}
if($flag == 'girl')
{
echo $strsearch.' exist, '. $strsearch.' is beautiful';
}
else
{
echo $strsearch.' not found. did you mean:';
}
?>

Related

Assign the same rank to student with the same scores

I'm assigning ranks to students based on their scores but I encountered a problem where if two or more students have the same scores they are given different ranks.
E.G John, Rita, and Mary scored 76. John is 1st, Rita is 2nd, and Mary is 3rd.
John ==> 76
Rita ==> 76
Mary ==> 76
Bukky ==>74
I want three of them to have the rank as 1st.
John ==> 76
Rita ==> 76
Mary ==> 76
Bukky ==>74
public function getStudentpositionOnlyClass($student_id, $class_id, $terms)
{
$array_product = array();
if ($class_id == 22 || $class_id == 23) {
if ($terms == 'f') {
$totField = 'ft_tot_score';
$table = 'ftscores_rn';
} elseif ($terms == 'm') {
$totField = 'mt_tot_score';
$table = 'mtscores_rn';
} elseif ($terms == 's') {
$totField = 'tot_score';
$table = 'scores_rn';
} elseif ($terms == 'h') {
$totField = 'h_tot_score';
$table = 'hscores_rn';
}
} else {
if ($terms == 'f') {
$totField = 'ft_tot_score';
$table = 'ftscores_primary';
} elseif ($terms == 'm') {
$totField = 'mt_tot_score';
$table = 'mtscores_primary';
} elseif ($terms == 's') {
$totField = 'tot_score';
$table = 'scores_primary';
} elseif ($terms == 'h') {
$totField = 'h_tot_score';
$table = 'hscores_primary';
}
}
$fail = 0;
$pass = 0;
$resultlist = $this->student_model->fullSearchByClass($class_id);
foreach ($resultlist->result_array() as $key => $stdName) {
$idd = $key + 1;
$mId[$idd] = $stdName['pstudent_id'];
$totalSubMarks = $this->db->query(
"SELECT mts.subject_id
FROM " . $table . " mts
LEFT JOIN subjects sub ON(sub.id=mts.subject_id)
WHERE class_id=" . $class_id .
" AND mts.subject_id IS NOT NULL
GROUP BY mts.subject_id ORDER BY sub.name");
$gtotal = 0;
$totSubjects = 0;
foreach ($totalSubMarks->result_array() as $tmrow) {
$totalMarks = $this->student_model->getTotalMarksForStudnets($tmrow['subject_id'],
$stdName['pstudent_id'], $table, $totField);
// //// set mtotalmark
$gtotal = $gtotal + $totalMarks;
// //// set mgtotal
$mGTotal[$idd] = $gtotal;
if ($totalMarks != 0) {
$totSubjects = $totSubjects + 1;
}
// //// set mAvg
if ($totSubjects != 0) {
$mAvg[$idd] = round($gtotal / $totSubjects, 1);
} else {
$mAvg[$idd] = 0;
}
}
// /////////
if ($totSubjects != 0) {
$percentage = ($gtotal / $totSubjects);
}
if ($percentage >= 0 && $percentage <= 39.99) {
$fail = $fail + 1;
} else {
$pass = $pass + 1;
}
}
foreach ($mAvg as $dd => $val) {
// if pure numbers store in nums array
if (! is_nan($val)) {
$nums[$dd] = $val;
}
}
arsort($nums);
$id = 1;
foreach ($nums as $kk => $av) {
foreach ($totalSubMarks->result_array() as $tmrow) {
$totalMarks = $this->student_model->getTotalMarksForStudnets($tmrow['subject_id'], $mId[$kk], $table,
$totField);
}
if ($student_id == $mId[$kk]) {
return $id;
}
// $array_product['student'.$mId[$kk]]= $id;
$id += 1;
}
}
As mickmackusa stated in his comment you have to memorize the previous score and only increment the rank if the score has changed. As you already order your results we can assume a score change between 2 iterations is always a decrease.
Your variable names are very unintuitive. So maybe my code changes are in the wrong place but you shoud understand the concept. I assume that $totSubjects is that score.
Try not to shorten a variable's name too much because you have no benifit but loose that important information on what it is. At least comment a variable assignment if its unclear what the variable holds of.
Change your loop like this:
$previousScore = null; // added THIS
foreach ($totalSubMarks->result_array() as $tmrow) {
$totalMarks = $this->student_model->getTotalMarksForStudnets($tmrow['subject_id'],
$stdName['pstudent_id'], $table, $totField);
// set mtotalmark
$gtotal = $gtotal + $totalMarks;
// set mgtotal
$mGTotal[$idd] = $gtotal;
if ($totalMarks != 0) {
if($previousScore != $totalMarks) { // added THIS
$totSubjects = $totSubjects + 1;
} else { // added THIS
$totSubjects = $totSubjects; // keep rank without incrementing
}
}
$previousScore = $totalMarks; // added THIS
// set mAvg
if ($totSubjects != 0) {
$mAvg[$idd] = round($gtotal / $totSubjects, 1);
} else {
$mAvg[$idd] = 0;
}
}
In case $gtotal or any of the other mystic variables ;) is holding the score then try to modify my given code changes to $gtotal. Shouldn't be too hard. In that case just add a comment so I can change my answer that it's actualy correct.
Hope that helps!

Search box not returning data (PHP)

I have a simple search box which allows me to search for a "Product ID". it will then read through my txt.file to find it. After reading, it will return the full information of the product based on the Product ID searched. As of right now, I'm having trouble returning the information of the product in the next page. I guess its because I don't really know how to compare the product IDs which are in a combination of strings, int and dashes and that's why it returns an empty result.
P.S: the first line of every element in my txt is the Product ID.
My Search Box
<html>
<body>
<div class="sn">
<form method="GET" action="fullInfo.php">
<p style="text-align: center;">Search for your musical instrument here!</p><br>
<input name ="sn" type="text" placeholder="Enter Product ID"><br>
<input type="submit" value="Search" class="submit" >
</form>
</div>
</body>
</html>
My Search Result (PHP)
<?php
$handle = #fopen('listings.txt', "r");
$row = 0;
$count = 0;
$line0 = [];
$line1 = [];
$line2 = [];
$line3 = [];
$line4 = [];
$line5 = [];
$line6 = [];
$line7 = [];
$line8 = [];
if ($handle) {
while (!feof($handle)) {
$store = fgets($handle, 4096);
if ($row == 10){
$row = 0;
$count++;
}
if ($row == 0)
{
$line0[] = strval($store);
}
else if($row == 1) {
$line1[] = strval($store);
}
else if($row == 2) {
$line2[] = strval($store);
}
else if($row == 3) {
$line3[] = strval($store);
}
else if($row == 4) {
$line4[] = strval($store);
}
else if($row == 5) {
$line5[] = strval($store);
}
else if($row == 6) {
$line6[] = strval($store);
}
else if($row == 7) {
$line7[] = strval($store);
}
else if($row == 8) {
$line8[] = strval($store);
}
$row++;
}
$sn = 0;
if (isset($_GET['sn'])) {
$sn=$_GET['sn'];
}
$item = count($line0);
for ($c=0; $c<$item; $c++)
{
if((intval(strnatcmp ($line0[$c], $sn)) == 0)) {
echo $line0[$c],"<br>";
echo $line1[$c],"<br>";
echo $line2[$c],"<br>";
echo $line3[$c],"<br>";
echo $line4[$c],"<br>";
echo $line5[$c],"<br>";
echo $line6[$c],"<br>";
echo $line7[$c],"<br>";
echo $line8[$c],"<br>";
break;
}
}
?>
<?php
fclose($handle);
}
?>
My listings.txt
abc-1234-99
Cedric
93482812
cedric#hotmail.com
Guitar
2000
Yamaha
null
New
---------------------------------------------
def-4332-99
Wendy
98238432
wendy#hotmail.com
Guitar
2010
Yamaha
Scratches on the side
Used
---------------------------------------------
fgh-4567-99
Wendy
98238432
wendy#hotmail.com
Guitar
2010
Yamaha
Scratches on the side
Used
---------------------------------------------

Loop from array not executed

I am working on an android app that should create some records on a MySQL database.
This is the PHP file that receives the POST values from the app.
As you may see, there are three arrays that collect specific POST.
The first and second loops are working fine and executing the related guardar_post_media() function.
But the third loop is not executed and there are real values on the variables inside the third array.
May be there is something wrong that I canĀ“t detect, may be you can.
<?php
require_once '../mis_php_functions/funciones_basicas.php';
if($_SERVER['REQUEST_METHOD']=='POST'){
$val39 = $_POST['val39'];
$val40 = $_POST['val40'];
$val46 = $_POST['val46'];
$val48 = $_POST['val48'];
$val50 = $_POST['val50'];
$val52 = $_POST['val52'];
$val54 = $_POST['val54'];
$val56 = $_POST['val56'];
$val58 = $_POST['val58'];
$val60 = $_POST['val60'];
$val62 = $_POST['val62'];
$val64 = $_POST['val64'];
$val65 = $_POST['val65'];
$val67 = $_POST['val67'];
$val69 = $_POST['val69'];
$val71 = $_POST['val71'];
$val73 = $_POST['val73'];
$val75 = $_POST['val75'];
$val77 = $_POST['val77'];
$val79 = $_POST['val79'];
$val81 = $_POST['val81'];
$val82 = $_POST['val82'];
$val83 = $_POST['val83'];
$val84 = $_POST['val84'];
$val85 = $_POST['val85'];
$val86 = $_POST['val86'];
$val87 = $_POST['val87'];
$val88 = $_POST['val88'];
$val89 = $_POST['val89'];
$val100 = $_POST['val100'];
$val101 = $_POST['val101'];
$val102 = $_POST['val102'];
$val103 = $_POST['val103'];
$val104 = $_POST['val104'];
$status = 1;
$post = guardar_post($val40,$val39,$val100,$val102,$status,$val103);
if ($post != false) {
$fotos = array($val48,$val50,$val52,$val54,$val56,$val58,$val60,$val62,$val64);
$arrayLength = count($fotos);
echo "Numero de fotos ".$arrayLength;
$i = 0;
while ($i < $arrayLength)
{
if ($fotos[$i] == 0){
}
else{
guardar_post_media(1,$fotos[$i],$val102,$val100,$post);
}
echo "<br />".$fotos[$i] ."<br />";
$i++;
}
$videos = array($val67,$val69,$val71,$val73,$val75,$val77,$val79,$val81,$val83);
$arrayLength2 = count($videos);
echo "Numero de videos ".$arrayLength2;
$i = 0;
while ($i < $arrayLength2)
{
if ($videos[$i] == 0){
}
else{
guardar_post_media(2,$videos[$i],$val102,$val100,$post);
}
echo "<br />".$videos[$i] ."<br />";
$i++;
}
$youtube = array($val85,$val86,$val87,$val88,$val89);
$arrayLength3 = count($youtube);
echo "Numero de youtube ".$arrayLength3;
$i = 0;
while ($i < $arrayLength3)
{
if ($youtube[$i] == 0){
}
else{
guardar_post_media(3,$youtube[$i],$val102,$val100,$post);
}
echo "<br />".$youtube[$i] ."<br />";
$i++;
}
sendMessageNuevoPost($val39,$val102,$val103,$val104); // envio de push
}
else{
echo 'error';
}
}
?>
You have:
if ($youtube[$i] == 0){
}
else {
}
But POST vars are all strings. Change to:
if ($youtube[$i] == "0"){
}
else {
}
In otherwords, an equality on a string to numerical 0 will be true in your cases. And thus your else never executes.
*** Edit. PROOF
$test1 = "filename.dat";
$test2 = "2939";
$test3 = "some useful data";
$test4 = "0";
if ($test1 == 0) {
// Dont do anything
}
else {
echo "Do Work 1.";
}
if ($test2 == 0) {
// Dont do anything
}
else {
echo "Do Work 2.";
}
if ($test3 == 0) {
// Dont do anything
}
else {
echo "Do Work 3.";
}
if ($test4 == 0) {
// Dont do anything
}
else {
echo "Do Work 4.";
}
Only echoes out Do Work 2.. All other echo()s are not run because the equality of a string to a number 0 will return true except in those cases where the string also is numerical, and then the interpreter will compare the numerical values.
As how this relates to the OP's question: It can be inferred that the OP's POST vars must contain some non-numerical data because the OP insists that the 3rd array is populated:
But the third loop is not executed and there are real values on the variables inside the third array.
I will add likely the loop is executed, but not giving the expected the results due the reasons so mentioned.
Tested on PHP 5 and 7.

Weird behaviour when searching for char in array string elements

<?php
ini_set('error_reporting', '-1');
ini_set('display_errors', '1');
ini_set('apc.enabled', '0');
gc_enable();
$array = array("php", "php_php", "php_php", "php_php", "php");
$arraysize = count($array);
$style = " style='border: 1px solid black;'";
$strcmpcharcount = 0;
$equalcmpcharcount = 0;
foreach ($array as $key)
{
$strcmpcharcount = 0;
$equalcmpcharcount = 0;
if (strstr($key, "_") !== false)
{
$strstr[] = "found";
$explodedstring1[] = explode("_", $key);
}
else
{
$strstr[] = "not found";
$explodedstring1[] = "not found";
}
if (strpos($key, "_") !== false)
{
$strpos[] = "found";
$explodedstring2[] = explode("_", $key);
}
else
{
$strpos[] = "not found";
$explodedstring2[] = "not found";
}
if (preg_match("/[^_+$]/", $key))
{
$preg_match[] = "found";
$explodedstring3[] = explode("_", $key);
}
else
{
$preg_match[] = "not found";
$explodedstring3[] = "not found";
}
$keysize = strlen($key);
for ($i = 0; $i < $keysize; $i++)
{
if (strcmp($key[$i], "_") === 0) { $strcmpcharcount++; }
}
for ($j = 0; $j < $keysize; $j++)
{
if ($key[$j] === "_") { $equalcmpcharcount++; }
}
if ($strcmpcharcount > 0)
{
$strcmp[] = "found";
$explodedstring4[] = explode("_", $key);
}
else
{
$strcmp[] = "not found";
$explodedstring4[] = "not found";
}
if ($equalcmpcharcount > 0)
{
$equalcmp[] = "found";
$explodedstring5[] = explode("_", $key);
}
else
{
$equalcmp[] = "not found";
$explodedstring5[] = "not found";
}
}
echo "<table$style>
<th$style>
<tr>
<td$style>strstr()</td>
<td$style>strpos()</td>
<td$style>preg_match()</td>
<td$style>strcmp()</td>
<td$style>'==='</td>
</tr>
</th>";
for($k = 0; $k < $arraysize; $k++)
{
echo "<tr>
<td$style>$strstr[$k]</td>
<td$style>$strpos[$k]</td>
<td$style>$preg_match[$k]</td>
<td$style>$strcmp[$k]</td>
<td$style>$equalcmp[$k]</td>
</tr>";
}
echo "</table>";
exit();
?>
The problem is with first two functions - they randomly fails to find the underscore char. In fact I called more than 50 times the script to got proper results. Added and preg_match() test but just to know I'm not sure if it has valid regex.
You're adding new elements to $strstr, $strpos tables and so on and in the end you do for... and printing from these tables where $k keys don't necessarily have to exists.
Check var_dump or print_r on these tables and you will see that in fact they got elements, but their indexes aren't matched with $array indexes (and i guess that's what you want to achieve).
You can change foreach ($array as $key) to foreach ($array as $index => $key) and all occurences like $strstr[] = "found"; to $strstr[$index] = "found"; (also for other recognision methods) and then run the script again to see results.
In last block (for($k = 0; $k < $arraysize; $k++)...) you should either validate if $strstr[$k] (and other arrays) exists before printing it, or print these arrays separately by foreach.
You can also make one table for results and make it multidimensional with function names as keys in the first level and put results in there.

Unxpected result when iterating nested arrays for merging content in PHP

I have 2 nested arrays over which I intent to iterate over one and insert into it a portion of a match in the other based on a key->value.
The idea is to iterate for each element of arrayA and nested iterate for each key->value of arrayB. When arrayA element equals to arrayB key->value i want to insert into arrayB a key->value of arrayA.
The problem I am having is that for some reason in the loop of arrayB it should iterate 78 times but is doing it only 2.
I know there is something messed up with the iterations but can't pin point.
Here is a sample of arrayA, arrayB and my code.
arrayA
arrayB
Here is my code
foreach($premiumContent as $prem_key => $targets)
{
$totCat = 0;
foreach($result as $category) //(result = 2 shop, ff) (category shop.designers, ff.restaurant)
{
$totCat = $totCat + 1;
$totFeatures = 0;
foreach($category as $features) //features = 1 designers, restaurants
{
$totFeatures = $totFeatures + 1;
//*********HERE IS THE PROBLEM IS NOT ITERATING BY THE LIST OF ALL FEATURES
$totFeature = 0;
foreach ($features as $feature) //stores
{
$totFeature = $totFeature + 1;
$properties = $feature[0]->properties;
if ($feature[0]->id == $prem_key)
{
if(count($targets[media]) > 0)
{
$properties->media = $targets[media];
}
else
{
$properties->media = '';
}
if(count($targets[offer]) > 0)
{
$properties->offer = $targets[offer];
}
else
{
$properties->offer = '';
}
if(count($targets[bi]) > 0)
{
$properties->bi = $targets[bi];
}
else
{
$properties->bi = '';
}
if(count($targets[info]) > 0)
{
$properties->info = $targets[info];
}
else
{
$properties->info = '';
}
}
}
}
}
}
return $result;
Could someone explain me what am I doing wrong? I am sure there is a better approach to this.
Here is the fix.
foreach($result as $category) //(result = 2 shop, ff) (category shop.designers, ff.restaurant)
{
$name = $category->dispName;
//echo $name;
foreach($category->list as $features) //features = 1 designers, restaurants
{
foreach ($features as $featureKey => $featureVal) //stores
{
$properties = $featureVal->properties;
if ($featureVal->id == $prem_key)
{
if(count($targets[media]) > 0)
{
$properties->media = $targets[media];
}
else
{
$properties->media = '';
}
if(count($targets[offer]) > 0)
{
$properties->offer = $targets[offer];
}
else
{
$properties->offer = '';
}
if(count($targets[bi]) > 0)
{
$properties->bi = $targets[bi];
}
else
{
$properties->bi = '';
}
if(count($targets[info]) > 0)
{
$properties->info = $targets[info];
}
else
{
$properties->info = '';
}
}
}
}
}
}

Categories