I've got a string here with names of students (leerlingen) and im trying to follow the exercise here.
The code shows the length of the full string.
Next up would be use a loop to check who has the longest name, but how to implement strlen() in a loop?
// change the string into an array using the explode() function
$sleerlingen = "Kevin,Maarten,Thomas,Mahamad,Dennis,Kim,Joey,Teun,Sven,Tony";
$namen = explode(" ", $sleerlingen);
echo $namen[0];
echo "<br><br>";
//determin the longest name by using a loop
// ask length
$arraylength = strlen($sleerlingen);
sleerlingen = $i;
for ($i = 1; $i <= 10; $i++) {
echo $i;
}
echo $arraylength;
?>
You used bad separator in your explode function, in string there is no space.
This should work (I didn't try it). In foreach loop you check current length with the longest one and if the current is longer, just save it as longest.
<?php
$sleerlingen = "Kevin,Maarten,Thomas,Mahamad,Dennis,Kim,Joey,Teun,Sven,Tony";
$names = explode(',', $sleerlingen);
$longest;
$longest_length = 0;
foreach ($names as $item) {
if (strlen($item) > $longest_length) {
$longest_length = strlen($item);
$longest = $item;
}
}
echo 'Longest name: ' . $longest . ', ' . $longest_length .' chars.';
?>
You can create a custom sort function to sort the array based on the strings length. Then you can easily take the first key in the array.
<?php
$sleerlingen = "Kevin,Maarten,Thomas,Mahamad,Dennis,Kim,Joey,Teun,Sven,Tony";
$namen = explode(",", $sleerlingen); // changed the space to comma, otherwise it won't create an array of the string.
function sortByLength($a,$b){
return strlen($b)-strlen($a);
}
usort($namen,'sortByLength');
echo $namen[0];
?>
Related
I am trying to sort data held in a variable. I first convert it to an array then try to sort it in ascending order but it seems not to be working.
Here is my code
$str = '"10:A", "11:Q", "12:V", "13:A", "14:G", "15:I", "16:E", "17:D", "18:N", "19:R", "1:A", "20:U", "2:X", "3:C", "4:D", "5:R", "6:U", "7:V", "8:I", "9:S"';
$cars = (explode(",",$str));
$cars = array($cars);
sort($cars, 1);
$clength=count($cars);
for($x=0;$x<$clength;$x++)
{
echo $cars[$x];
echo "<br>";
}
Any workaround this?
try rsort
$str = '"10:A", "11:Q", "12:V"';
$cars = (explode(",",$str));
rsort($cars);
$clength=count($cars);
for($x=0;$x<$clength;$x++)
{
echo $cars[$x];
echo "<br>";
}
If you want to sort according to number try this:
<?php
function my_sort($a,$b)
{
$intval_a = filter_var($a, FILTER_SANITIZE_NUMBER_INT);
$intval_b = filter_var($b, FILTER_SANITIZE_NUMBER_INT);
if(intval($intval_a) > intval($intval_b))
return 1;
}
$str = '"10:A", "11:Q", "12:V", "13:A", "14:G", "15:I", "16:E", "17:D", "18:N", "19:R", "1:A", "20:U", "2:X", "3:C", "4:D", "5:R", "6:U", "7:V", "8:I", "9:S"';
$cars = explode(',',$str);
$cars = ($cars);
usort($cars, "my_sort");
$clength=count($cars);
for($x=0;$x<$clength;$x++)
{
echo $cars[$x];
echo "<br>";
}
There are a couple of things I've noticed. First, you've exploded the string which produces an array. You're then putting that array into another array and trying to sort that. You should remove the line $cars = array($cars);
I'd also recommend removing the quotes and spaces from the string before trying to sort them, so you are doing the sort on 10:A instead of "10:A", for example.
The other thing is the sort function should take a flag as the second parameter which defines the type of sort to perform. See the docs for the different flags you have available. I'm guessing you want it to be sorted
1:A, 2:X, 3:C...
instead of
1:A, 10:A, 11:Q...
in which case you should use the SORT_NATURAL flag. (Alternatively, you could use the natsort function).
These changes would give the following code:
$str = '"10:A", "11:Q", "12:V", "13:A", "14:G", "15:I", "16:E", "17:D", "18:N", "19:R", "1:A", "20:U", "2:X", "3:C", "4:D", "5:R", "6:U", "7:V", "8:I", "9:S"';
$str = str_replace(array('"', ' '), '', $str);
$cars = explode(",",$str);
sort($cars, SORT_NATURAL);
$clength = count($cars);
for($x = 0; $x < $clength; $x++) {
echo $cars[$x];
echo "<br>";
}
use natsort() function
$str = '"10:A", "11:Q", "12:V", "13:A", "14:G", "15:I", "16:E", "17:D", "18:N", "19:R", "1:A", "20:U", "2:X", "3:C", "4:D", "5:R", "6:U", "7:V", "8:I", "9:S"';
$cars = (explode(",",$str));
natsort($cars);
echo "<pre>"; print_r($cars);
foreach($cars as $car)
{
echo $car."<br>";
}
Check here
Hope this will help.
I need to convert my array:
$tdata = array(11,3,8,12,5,1,9,13,5,7);
Into a string like this:
11-3-8-12-5-1-9-13-5-7
I was able to get it work with:
$i = 0;
$predata = $tdata[0];
foreach ($tdata as $value)
{
$i++;
if ($i == 10) {break;}
$predata.='-'.$tdata[$i];
}
But was wondering if there is an easier way?
I tried something like:
$predata = $tdata[0];
foreach ($tdata as $value)
{
if($value !== 0) {
$predata.= '-'.$tdata[$value];
}
}
but it result in bunch of Undefined Offset errors and incorrect $predata at the end.
So I want to learn once and for all:
How to loop through the entire array starting from index 1 (while excluding index 0)?
Is there a better approach to convert array into string in the fashion described above?
Yes there is a better approach to this task. Use implode():
$tdata = array(11,3,8,12,5,1,9,13,5,7);
echo implode('-', $tdata); // this glues all the elements with that particular string.
To answer question #1, You could use a loop and do this:
$tdata = array(11,3,8,12,5,1,9,13,5,7);
$out = '';
foreach ($tdata as $index => $value) { // $value is a copy of each element inside `$tdata`
// $index is that "key" paired to the value on that element
if($index != 0) { // if index is zero, skip it
$out .= $value . '-';
}
}
// This will result into an extra hypen, you could right trim it
echo rtrim($out, '-');
In my php script, I have a variable $data that contains an array that may have various number of elements.
The script picks one of the array elements at random and outputs it to the browser:
# count number of elements in $data
$n = count($data);
# pick a random number out of the number of elements in $data
$rand = rand(0, ($n - 1));
# output a random element
echo '<p> . trim($data[$rand]) . '</p>';
QUESTION: I want to improve that script, so that it doesn't output the same array element again until it runs out of array elements. For example, if an array contains elements numbered 0 to 9, and the script picked an array element #4, I want it to remember that, and next time the script runs, to exclude the element that was #4.
It could probably be done in many different ways, but I'm looking for the simplest and most elegant solution, and would be grateful for help from a PHP expert.
Save the numbers that were already picked in the user's session.
session_start();
$n = count($data);
// If the array isn't initialized, or we used all the numbers, reset the array
if( !isset( $_SESSION['used_nums']) || count( $_SESSION['used_nums']) == $n) {
$_SESSION['used_nums'] = array();
}
do{
$rand = rand(0, ($n - 1));
} while( isset( $_SESSION['used_nums'][$rand]));
echo '<p>' . trim($data[$rand]) . '</p>';
$_SESSION['used_nums'][$rand] = 1;
Or, perhaps a more clever way, using array_intersect_key and array_rand:
session_start();
$n = count($data);
// If the array isn't initialized, or we used all the numbers, reset the array
if( !isset( $_SESSION['used_nums']) || count( $_SESSION['used_nums']) == $n) {
$_SESSION['used_nums'] = array();
}
$unused = array_intersect_key( $data, $_SESSION['used_nums'];
$rand = array_rand( $unused);
echo '<p>' . trim($unused[$rand]) . '</p>';
$_SESSION['used_nums'][$rand] = 1;
You could shuffle the array and then simply iterate over it:
shuffle($data);
foreach ($data as $elem) {
// …
}
If you don’t want to alter the array order, you could simply shuffle the array’s keys:
$keys = array_keys($data);
shuffle($keys);
foreach ($keys as $key) {
// $data[$key]
}
You can use sessions to store the indexes you've used so far. Try this.
session_start();
$used = &$_SESSION['usedIndexes'];
// used all of our array indexes
if(count($used) > count($data))
$used = array();
// remove the used indexes from data
foreach($used as $index)
unset($data[$index]);
$random = array_rand($data);
// append our new index to used indexes
$used[] = $random;
echo '<p>', trim($data[$random]) ,'</p>';
$selection=$x[$randomNumber];
unset($x[$randomNumber]);
I would need to reduce the quantity of these numbers and present them in a more concise way, instead of presenting several lines of numbers with the same "prefix" or "root". For example:
If I have an array like this, with several strings of numbers (obs: only numbers and the array is already sorted):
$array = array(
"12345647",
"12345648",
"12345649",
"12345657",
"12345658",
"12345659",
);
The string: 123456 is the same in all elements of the array, so it would be the root or the prefix of the number. According to the above array I would get a result like this:
//The numbers in brackets represent the sequence of the following numbers,
//instead of showing the rows, I present all the above numbers in just one row:
$stringFormed = "123456[4-5][7-9]";
Another example:
$array2 = array(
"1234",
"1235",
"1236",
"1247",
"2310",
"2311",
);
From the second array, I should get a result like this:
$stringFormed1 = "123[4-7]";
$stringFormed2 = "1247";
$stringFormed3 = "231[0-1]";
Any idea?
$array = array(
"12345647",
"12345648",
"12345649",
"12345657",
"12345658",
"12345659",
);
//find common string positions for all elements
$res = array();
foreach($array as $arr){
for($i=0;$i<strlen($arr);$i++){
$res[$i][$arr[$i]] = $arr[$i];
}
}
//make final string
foreach($res as $pos){
if(count($pos)==1)
$str .= implode('',$pos);
else{
//u may need to sort these values if you want them in order
$end = end($pos);
$first = reset($pos);
$str .="[$first-$end]";
}
}
echo $str; // "123456[4-5][7-9]";
Well, as I understand you want the final string with unique characters. (i'm not sure if you want it ordered)
So, first implode to create the string
$stringFormed = implode("", $array);
Then we get the unique chars :
$stringFormed=implode("",array_unique(str_split($stringFormed)));
OUTPUT: 123456789
That as a solution for first example but i didn't thought there could be several roots.
By the way i'm not sure it's well coded...
<?php
function longest_common_substring($words)
{
$words = array_map('strtolower', array_map('trim', $words));
$sort_by_strlen = create_function('$a, $b', 'if (strlen($a) == strlen($b)) { return strcmp($a, $b); } return (strlen($a) < strlen($b)) ? -1 : 1;');
usort($words, $sort_by_strlen);
// We have to assume that each string has something in common with the first
// string (post sort), we just need to figure out what the longest common
// string is. If any string DOES NOT have something in common with the first
// string, return false.
$longest_common_substring = array();
$shortest_string = str_split(array_shift($words));
while (sizeof($shortest_string)) {
array_unshift($longest_common_substring, '');
foreach ($shortest_string as $ci => $char) {
foreach ($words as $wi => $word) {
if (!strstr($word, $longest_common_substring[0] . $char)) {
// No match
break 2;
} // if
} // foreach
// we found the current char in each word, so add it to the first longest_common_substring element,
// then start checking again using the next char as well
$longest_common_substring[0].= $char;
} // foreach
// We've finished looping through the entire shortest_string.
// Remove the first char and start all over. Do this until there are no more
// chars to search on.
array_shift($shortest_string);
}
// If we made it here then we've run through everything
usort($longest_common_substring, $sort_by_strlen);
return array_pop($longest_common_substring);
}
$array = array(
"12345647",
"12345648",
"12345649",
"12345657",
"12345658",
"12345659",
);
$result= longest_common_substring($array);
for ($i = strlen($result); $i < strlen($array[0]); $i++) {
$min=intval($array[0][$i]);
$max=$min;
foreach ($array as $string) {
$val = intval($string[$i]);
if($val<$min)
$min=$val;
elseif($val>$max)
$max=$val;
}
$result.='['.$min.'-'.$max.']';
}
echo $result;
?>
So I have fields that are generated dynamically in a different page and then their results should posted to story.php page. fields is going to be : *noun1 *noun2 *noun3 and story is going to be : somebody is doing *noun1 etc. What I want to do is to replace *noun1 in the story with the *noun, I have posted from the previous page ( I have *noun1 posted from the previous page ) but the code below is not working :
$fields = $_POST['fields'];
$story = $_POST['story'];
$fieldsArray = split(' ', $fields);
for ($i = 0; $i < count($fieldsArray); $i++) {
${$fieldsArray[$i]} = $_POST[$fieldsArray[$i]];
}
// replace words in story with input
for ($i = 0; $i < count($story); $i++) {
$thisWord = $story[$i];
if ($thisWord[0] == '*')
$story[$i] = ${$thisWord.substring(1)};
}
$tokensArray = split(' ',$tokens);
echo $story;
Your problem is likely that you are trying to echo $story, which I gather is an array. You might have better luck with the following:
$storyString = '';
for ($i = 0; $i < count($story); $i++)
{
$storyString .= $story[i] . ' ';
}
echo $storyString;
echo can't print an array, but you can echo strings to your heart's content.
You almost certainly don't want variable variables (e.g. ${$fieldsArray[$i]}). Also, $thisWord.substring(1) looks like you're trying to invoke a method, but that's not what it does; . is for string concatenation. In PHP, strings aren't objects. Use the substr function to get a substring.
preg_replace_callback can replace all your code, but its use of higher order functions might be too much to get into right now. For example,
function sequence($arr) {
return function() {
static $i=0
$val = $arr[$i++];
$i %= count($arr);
return $val;
}
}
echo preg_replace_callback('/\*\w+/', sequence(array('Dog', 'man')), "*Man bites *dog.");
will produce "Dog bites man." Code sample requires PHP 5.3 for anonymous functions.