How Can I Extract the stringlength higher word in an array? - php

In the first time, I'm sorry for my disastrous english.
After three days trying to solve this, i give up.
Giving this array:
$names = array ( "James Walter Case", "Benjamin Wallace Pinkman", "Billy Elliot Newson" )
I have to extract the full name of the higher first stringlength word of each full name.
In this case, considering this condition Benjamin will be the higher name. Once
this name extracted, I have to print the full name.
Any ideas ? Thanks

How about this?
$names = array ( "James Walter Case", "Benjamin Wallace Pinkman", "Billy Elliot Newson" );
if (count($names) > 0)
{
$higher_score = 0;
foreach ($names as $name_key => $name_value)
{
$name_array = explode(" ", $name_value);
// echo("<br><b>name_array -></b><pre><font FACE='arial' size='-1'>"); print_r($name_array); echo("</font></pre><br>");
$first_name = $name_array[0];
// echo "first_name -> ".$first_name."<br>";
$score = strlen($first_name);
// echo "score -> ".$score."<br>";
if ($score > $higher_score)
{
$higher_score = $score;
$winner_key = $name_key; }
}
reset($names);
}
echo("longest first name is ".$names[$winner_key]." with ".$higher_score." letters.");

As said before, you can use array_map to get all the lenghts of the first strings, and then get the name based on the key of that value.
$names = array ( "James Walter Case", "Benjamin Wallace Pinkman", "Billy Elliot Newson" );
$x = array_map(
function ($a) {
$x = explode (" ", $a); // split the string
return strlen($x[0]); // get the first name
}
, $names);
$maxs = array_keys($x, max($x)); // get the max values (may have equals)
echo $names[$maxs[0]]; // get the first max
-- EDIT
Actually, there is a better way of doing this, considering this case. You can simply order the array by the lenght of the first names, and then get the first key:
usort($names,
function ($a, $b) {
$aa = explode(" ", $a); // split full name
$bb = explode(" ", $b); // split full name
if (strlen($aa[0]) > strlen($bb[0])){
return 0; // if a > b, return 0
} else {
return 1; // else return 1
}
}
);
echo $names[0]; // get top element

Allow me to provide a handmade solution.
<?php
$maxLength = 0;
$fullName = "";
$parts = array();
foreach($names as $name){
/* Exploding the name into parts.
* For instance, "James Walter Case" results in the following array :
* array("James", "Walter", "Case") */
$parts = explode(' ', $name);
if(strlen($parts[0]) > $maxLength){ // Compare first length to the maximum.
$maxLength = strlen($parts[0]);
$fullName = $name;
}
}
echo "Longest first name belongs to " . $fullName . " (" . $maxLength . " character(s))";
?>
Basically, we iterate over the array, split each name into parts (delimited by spaces), and try to find the maximum length among first parts of names ($parts[0]). This is basically a maximum search algorithm.
There may be better ways with PHP array_* functions, but well, this one gets pretty self-explanatory.

You can try something like..
$maxWordLength=0;
$maxWordIndex=null;
foreach ($names as $index=>$name){
$firstName=first(explode(' ',$name));
if (strlen($firstName)>maxWordLength){
$maxWordLength=strlen($firstName);
$maxWordIndex=$index;
}
}
if ($maxWordIndex){
echo $names[$maxWordIndex];
}

Related

how to get the count of specific letters occurances from a array of words

i want to get the count of some text that starts with specific letter with "/"
just like as follows. i want the count of all "A/" occurancves in that array.
<?php
$arr_vals = array("A/V","A/B","B/A","D/D","A/v","A/A");
$count_A = count($arr_vals,"A/*");
?>
Simple and easy one..Here is your solution:-
$input = preg_quote('A/', '~'); // don't forget to quote input string!
$arr_vals = array("A/V","A/B","B/A","D/D","A/v","A/A");
$result = preg_grep('~' . $input . '~', $arr_vals);
echo count($result); die;
array_reduce can be used to take your entire array and compute a result, through the use of a callback function. We can use regular expressions to define what your pattern is. Combining these two things, we have your solution:
$arr_vals = array("A/V","A/B","B/A","D/D","A/v","A/A");
function match($carry, $item) {
return $carry + preg_match('/A\/./', $item);
}
var_dump(array_reduce($arr_vals, 'match', 0)); // Returns 4
Using fnmatch would also work and uses shell wildcards, e.g. * and ?:
function count_pattern(array $input, string $pattern): int {
$count = 0;
foreach ($input as $string) {
$count += fnmatch($pattern, $string);
}
return $count;
}
Usage
$arr_vals = array("A/V","A/B","B/A","D/D","A/v","A/A");
echo count_pattern($arr_vals, "A/*"); // 4
Note: in order to use scalar type hints and returns you need PHP7. If you are not on PHP7 yet, you can just omit them.
Yes the correct answer is
$input = preg_quote('A/', '~'); // don't forget to quote input string!
$arr_vals = array("A/V","A/B","B/A","D/D","A/v","A/A");
$result = preg_grep('~' . $input . '~', $arr_vals);
echo count($result); die;

Last name usort

I asked a similar question but still having issues when some aspects.
The way this php file is working is that a persons name is being stored in the database in the names cell, in the format John Doe(firstname lastname). So I've separated the name with this code, so surname, firstname:
foreach ($customer_names as $key => $value) {
$parts = explode(" ", $value->name);
$lastname = array_pop($parts);
$firstname = implode(" ", $parts);
$name = $lastname.", ".$firstname." ";
echo "<option value='$value->name'>$name </option>";
now that gives me a list of names like Doe, John.
However, I need to sort the names in order of the surname.
using usort. How would I do that? I've tried playing around with the code, but still is showing up in the order of the first name (set by the db query).
Still a bit new to usort functionality.
This should work:
usort($customer_names, function($customer1, $customer2) {
return strcmp(
substr($customer1->name, strrpos($customer1->name, " ")),
substr($customer2->name, strrpos($customer2->name, " "))
);
});
Your $customer_names array will then be sorted by the last name of the customer. Last name means the string after the last space, e.g. John Doe would be Doe. Mary Lou Foo would be Foo.
Please refer to http://php.net to learn more about the used functions.
//Program for sorting list of names according to last name
<?php
class array_sort
{
public $temp;
public function alhsort(array $sorted)
{
for($i=0; $i<count($sorted)-1; $i++){
for($j=$i+1; $j<count($sorted); $j++){
if(strcasecmp(end(explode(' ', $sorted[$i])), end(explode(' ', $sorted[$j])))>0){
$temp = $sorted[$i];
$sorted[$i] = $sorted[$j];
$sorted[$j] = $temp;
}
}
}
return $sorted;
}
}
$sortarray = new array_sort();
print_r($sortarray->alhsort(array('Ayush Jain', 'Abhishek Gupta', 'Rahul Rajput', 'Kapil Patel', 'Shobit Shrivastav', 'Hitesh Gupta')));
?>

Unset rand() output from array in php

I want to remove $win value from array and print all names except to winner. please check below code.
<html>
<p>
<?php
// Create an array and push on the names
// of your closest family and friends
$array=array();
array_push( $array,"preet");
array_push($array,"limbu");
array_push($array,"nik");
array_push($array,"rohit");
array_push($array,"ravi");
// Sort the list
sort($array);
echo"all guys are ".$f=join(", ",$array);
echo"<br>Lets see who is winner</br> ";
$len=count($array);
// Randomly select a winner!
$win=strtoupper( $array[rand(0,$len-1)]);
// Print the winner's name in ALL CAPS
echo "$win";
//print name of all except to winner.but given below code is not working
unset($win);
print"<br> sory ".join(",",$array);
You have to unset the entry of the winner in your $array
<?php
// Create an array and push on the names
// of your closest family and friends
$array = array();
array_push($array, "preet");
array_push($array, "limbu");
array_push($array, "nik");
array_push($array, "rohit");
array_push($array, "ravi");
// Sort the list
sort($array);
echo"all guys are " . $f = join(", ", $array);
echo"<br>Lets see who is winner</br> ";
$len = count($array);
// Randomly select a winner!
$random = rand(0, $len - 1);
$win = strtoupper($array[$random]);
// Print the winner's name in ALL CAPS
echo $win;
//print name of all except to winner.but given below code is not working
unset($array[$random]);
print"<br> sory " . join(",", $array);
You need to know the index of the value in the array to remove the item from the array.
You can do this using the array_search function and then use unset to remove the value.
if(($key = array_search($win, $array)) !== false) {
unset($array[$win]);
}

PHP compare two arrays from different locations

I am wanting to compare two different arrays. Basically I have a database with phrases in and on my website I have a search function where the user types in a phrase.
When they click search I have a PHP page which 'explodes' the string typed in by the user and its put into an array.
Then I pull all the phrases from my database where I have also used the 'explode' function and split all the words into an array.
I now want to compare all the arrays to find close matches with 3 or more words matching each phrase.
How do I do this?
Well what I've tried totally failed, but here is what I have
$search_term = filter_var($_GET["s"], FILTER_SANITIZE_STRING); //user entered data
$search_term = str_replace ("?", "", $search_term); //removes question marks
$array = explode(" ", $search_term); //breaks apart user entered data
foreach ($array as $key=>$word) {
$array[$key] = " title LIKE '%".$word."%' "; //creates condition for MySQL query
}
$q = "SELECT * FROM posts WHERE " . implode(' OR ', $array) . " LIMIT 0,10";
$r = mysql_query($q);
while($row = mysql_fetch_assoc($r)){
$thetitle = $row['title'];
$thetitle = str_replace ("?", "", $thetitle);
$title_array[] = $thetitle;
$newarray = explode(" ", $search_term);
foreach ($newarray as $key=>$newword) {
foreach($title_array as $key => $value) {
$thenewarray = explode(" ", $value);
$contacts = array_diff_key($thenewarray, array_flip($newarray));
foreach($contacts as $key => $value) {
echo $newword."<br />";
echo $value."<br /><hr />";
}
}
}
But basically all I want is to display suggested phrases which are similar to what the user has already typed into the search box.
So If I searched "How do I compare two arrays that have the same values?", I would see 10 suggestions that are worded similar, so like "How to compare multiple arrays?" or "can I compare two arrays" etc...
So basically like when I first posted this question on this site, I got other questions that may help, thats basically what I want. This code im using was origionally to match just one word or an exact matching string, im editing it to find matching words and only show phrases with 3 or more matching words.
I don't think that this is the best solution for your search script. But I'll try to give you the answer:
<?php
$string1 = "This is my first string";
$string2 = "And here is my second string";
$array1 = explode(" ", $string1);
$array2 = explode(" ", $string2);
$num = 0;
foreach($array1 as $arr) {
if(in_array($arr, $array2))
$num++;
}
$match = $num >= 3 ? true : false;
?>
use array_intersect function
$firstArray = "This is a test only";
$secondArray = "This is test";
$array1 = explode(" ", $firstArray);
$array2 = explode(" ", $secondArray);
$result = array_intersect($array1, $array2);
$noOfWordMatch = count($result);
$check = $noOfWordMatch >= 3 ? true : false; ;

PHP problems parsing a bible book string

I hope you can help me.
I have a string like the following
Luke 1:26-38
And I would like to be able to break it up into tokens or individual variables so that I can use the variables in an SQL query.
I've tried using explode, however I've only been able to make it explode on one character such as : or -
My string has : and - and also a space between the name and the first number.
My goal is to have:
$name = Luke;
$book = 1;
$from = 26;
$to = 38;
Is anyone able to help please.
Many thanks
You can do that with a simple string scanning (Demo):
$r = sscanf("Luke 1:26-38", "%s %d:%d-%d", $name, $book, $from, $to);
The varibales then contain the information. %s represents a string (without spaces), %d a decimal. See sscanf.
To make this "bible safe", it needs some additional modifications:
$r = sscanf($string, "%[ a-zA-Z] %d:%d-%d", $name, $book, $from, $to);
$name = trim($name);
(Second demo).
list( $name, $book, $from, $to ) = preg_split( '/[ :-]/', 'Luke 1:26-38' );
echo $name; //"Luke"
/* Split results in an Array
(
[0] => Luke
[1] => 1
[2] => 26
[3] => 38
)
*/
$string = "Luke 1:26-38";
preg_match('#^(\w+)\s(\d+):(\d+)-(\d+)$#', $string, $result);
print_r($result);
regex is hard to configure for this because of the multiple configurations of bible book names, chapter and verse num. Because some books begin with a number and some books have multiple spaces in the book names.
I came up with this for building a sql query, it works for these passage search types..
(John), (John 3), (Joh 3:16), (1 Thes 1:1)
Book names can be 3 letter abbreviations.
Does unlimited individual word search and exact phrase.
$string = $_GET['sstring'];
$type = $_GET['stype'];
switch ($type){
case "passage":
$book = "";
$chap = "";
$stringarray = explode(':', $string); // Split string at verse refrence/s, if exist.
$vref = $stringarray[1];
$vrefsplit = explode('-', $vref);// Split verse refrence range, if exist.
$minv = $vrefsplit[0];
$maxv = $vrefsplit[1]; // Assign min/max verses.
$bc = explode(" ", $stringarray[0]); // Split book string into array with space as delimiter.
if(is_numeric($bc[count($bc)-1])){ // If last book array element is numeric?
$chap = array_pop($bc); // Remove it from array and assign it to chapter.
$book = implode(" ", $bc); // Put remaining elemts back into string and assign to book.
}else{
$book = implode(" ", $bc); // Else book array is just book, convert back to string.
}
// Build the sql query.
$query_rs1 = "SELECT * FROM kjvbible WHERE bookname LIKE '$book%'";
if($chap != ""){
$query_rs1.= " AND chapternum='$chap'";
}
if($maxv != ""){
$query_rs1.= " AND versenum BETWEEN '$minv' AND '$maxv'";
}else if($minv != ""){
$query_rs1.= " AND versenum='$minv'";
}
break;
case "words":
$stringarray = explode(" ", $string); // Split string into array.<br />
// Build the sql query.
$query_rs1 = "SELECT * FROM kjvbible WHERE versetext REGEXP '[[:<:]]". $stringarray[0] ."[[:>:]]'";
if(count($stringarray)>1){
for($i=1;$i<count($stringarray);$i++){
$query_rs1.= " AND versetext REGEXP '[[:<:]]". $stringarray[$i] ."[[:>:]]'";
}
}
break;
case "xphrase":
// Build the sql query.
$query_rs1 = "SELECT * FROM kjvbible WHERE versetext REGEXP '[[:<:]]". $string ."[[:>:]]'";
break;
default :
break;
}

Categories