I've got a bit of a problem, I have 2 inputs, one to type words, the other to find a keyword in the word array,
My code looks like this
if (isset($_POST['ord'])){
$name = $_POST['ord'];
$searchWord = $_POST['sök'];
$nameArray = (explode(" ", $name));
foreach ($nameArray as $key => $value) {
if ($value === $searchWord) {
echo substr_count($name, $value) ;
echo "<br>";
echo array_keys($value, $name);
break;
}
}
}
The problem I have is with this line
echo array_keys($value, $name);
I can only get it to call out the position of the index once before it stops, I want it to call out all the index positions, In this cause it would be 2 and 4
It might also have to do with the break; but then the problem remains that the break prevents the first line to repeat which is why I added it
This is what the output looks like (Can't post image yet)
Array ( [0] => hi [1] => Hey [2] => hi [3] => Hey )
The word Hey was found 2 times
Warning: array_keys() expects parameter 1 to be array, string given in C:\wamp64\www\labb-1a-php-sidor\sida3.php on line 39
You don't need a loop. Just call array_keys() correctly -- the first argument should be the array.
if (isset($_POST['ord'])){
$name = $_POST['ord'];
$searchWord = $_POST['sök'];
$nameArray = (explode(" ", $name));
$result = array_keys($nameArray, $searchWord);
echo "The word $searchWord was found " . count($result) . " times<br>";
var_dump($result);
}
Related
This question already has answers here:
How to output which indexes ive found an element in an array
(4 answers)
Closed 2 years ago.
I've got a bit of a problem, I have 2 inputs, one to type words, the other to find a keyword in the word array,
My code looks like this
<form class="" action="sida3.php" method="post" >
<label for="ord">Ord</label>
<input type="text" name="ord" value="">
<label for="sök">Sökord</label>
<input type="text" name="sök" value="">
<button type="submit" name="button">Submit</button>
</form>
if (isset($_POST['ord'])){
$name = $_POST['ord'];
$searchWord = $_POST['sök'];
$nameArray = (explode(" ", $name));
foreach ($nameArray as $key => $value) {
if ($value === $searchWord) {
echo "The word ". $value .' was found ' . substr_count($name, $value) . " times";
echo "<br>";
echo "The word ". $value .' is found in position: ' . array_keys($nameArray, $value);
break;
}
}
}
The problem I have is with this line echo array_keys($value, $nameArrray);
Using array_search($value,$nameArray) results to the following output
The Word Hey is found in position: 1
I can get it to call out the position of the index once before it stops, I want it to call out all the index positions, In this cause it would be 1 and 3
It might also have to do with the break; but then the problem remains that the break prevents the whole string from repeating itself, which is why I added it
This is what the output looks like (If you type the words "hi Hey hi Hey" in the "ord" input)
Array ( [0] => hi [1] => Hey [2] => hi [3] => Hey )
The word Hey was found 2 times
Warning: array_keys() expects parameter 1 to be array, string given in C:\wamp64\www\labb-1a-php-sidor\sida3.php on line 39
The desired output should look like this
Array ( [0] => hi [1] => Hey [2] => hi [3] => Hey )
The word Hey Was found 2 times
The Word Hey is found in position: 1 3
In your original version you had the parameters the wrong way round in your input to array_keys - the array must be first, followed by the search value. (The version you're showing after editing the question wouldn't produce the error you mentioned, but the first one would.)
Also, array_keys returns an array and you can't echo that directly (PHP has no idea how you actually want it to appear visually), so you'll need to implode it.
foreach ($nameArray as $key => $value) {
if ($value === $searchWord) {
echo "The word ". $value .' was found ' . substr_count($name, $value) . " times";
echo "<br>";
echo "The word ". $value .' is found in position(s): ' . implode(",", array_keys($nameArray, $value));
break;
}
}
Working demo: http://sandbox.onlinephpfunctions.com/code/a1980664a7b4f8e27f7c2a1aa04ebabee5379037
P.S. You can make this a lot more efficient, there's no need for looping or substrings. Simply count the number of matching keys. You can replace all the code I showed above with just this:
$positions = array_keys($nameArray, $searchWord);
echo "The word '". $searchWord . "' is found ". count($positions) . " time(s), in position(s): " . implode(",", $positions);
Demo: http://sandbox.onlinephpfunctions.com/code/7251b2f87b7355acf5c9242cb6ceba2ea08a9b98
Your code at
echo '...' . array_keys($nameArray, $value);
will not be able to print because array_keys will return an array of keys (or indices) instead of a value (integer or string).
To print out an array, try one of the following approaches.
var_dump(array_keys(...));
print_r(array_keys(...));
foreach(array_keys(...) as $value) {
echo $value;
}
When using an array in a foreach loop
$stdlist = rtrim(trim($_POST['stdlist'], '/'), '/');
$stdlist = explode('/' , $stdlist);
print_r($stdlist);
foreach($stdlist as $value)
{
echo "<br>";
echo $_POST[$value];
}
the array $stdlist is clearly working; when printed this returns:
Array ( [0] => 1 [1] => 6 [2] => 7 [3] => 8 )
My problem is that when I use the foreach loop to extract out of the array one value at a time, the following gets printed to the page:
4
4
Notice: Undefined offset: 7 in C:\Program Files\wamp\www...on line 35
Notice: Undefined offset: 7 in C:\Program Files\wamp\www...on line 35
I know this isn't functioning as intended as I am expecting the following:
1
6
7
8
Could somebody please explain why this is happening and how to fix this issue? Thanks :-)
You have to print the $value bacause $value have original array value not index.
And you are getting array in $stdlist from exploding this post variable $_POST['stdlist'].
foreach($stdlist as $value)
{
echo "<br>";
echo $value;
}
Now you will get your required result.
instead of using echo $_POST[$value]; just use echo $value when you use foreach loop for an array, the values on each nodes are automatically extracted.
foreach ($array as $index=>$value){
echo "index is $index and value associated with it is $value.";
}
Hope this helps.
foreach($stdlist as $value)
{
echo "<br>";
echo $value;
}
when you use foreach the $value is not the position in the array, if you want to use the position you need to do
for($pos=0; $pos<sizeof($stdlist); $pos++)
{
echo "<br>";
echo $stdlist[$pos];
}
When using the foreach() loop, I'd recommend assigning both the position and value to their own respective variables and then print them to the screen to see how the foreach loop has assigned the values.
foreach( $stdlist as $position => $value ) {
echo "The current position is $position, and the value of \$stdlist[$position] is
$value";
}
I'm trying to make a script to remove any empty elements from my array.
However an empty element is in the [0] slot so when I unset the value it deletes my whole array. At least I think that's what's happening, why isn't this working?
<?php
$idfile = file_get_contents("datafile.dat");
$idArray = explode("\n", $idfile);
print_r($idArray);
foreach ($idArray as $key => &$value) {
echo "Key is: ".$key." and value is: ".$value."<br />\n";
if ($value == ""){
echo "Killing value of ".$value."<br />";
unset($value[$key]);
}
$value = str_replace("\n", "", $value);
$value = str_replace("\r", "", $value);
$value = $value.".dat";
}
print_r($idArray);
?>
Here's the output:
Array
(
[0] =>
[1] => test1
[2] => test2
)
Key is: 0 and value is: <br>
Killing value of <br>
If you are just removing an empty value try using unset($idArray[$key]) instead. If you are just trying to remove the first element overall, use array_shift()
Another nice solution would be to use the array_filter() method, which will handle the iteration and return the filtered array for you:
<?php
function isNotEmpty($str)
{
return strlen($str);
}
$idfile = file_get_contents("datafile.dat");
$idArray = explode("\n", $idfile);
$idArray = array_filter($idArray, "isNotEmpty");
?>
i have a while loop, it goes like so....
while ($fruit_name = current($data)) {
$string1 .= "'".key($data)."',";
next($data);
}
this works perfectly, and echos:
'derp','test'
when the array data =
Array ( [derp] => 68 [test] => 1 )
but, if the array data =
Array ( [derp] => 0 [test] => 0 )
it echos
nothing,
what do?
If you want to traverse an array manually, you must use each since there is - as you found out - no way to differentiate the negative result from current and a false-valued value. Even if you were to check with === false, you'd still fail if the array contained a false entry.
However, you should really just use foreach instead:
foreach ($data as $k=>$fruit_name) {
$string1 .= "'". $k . "',";
}
PHP counts 0 as false which terminates your while loop, to allow 0 you would need to do a type-sensitive comparison:
while (($fruit_name = current($data)) !== false) {
$string1 .= "'".key($data)."',";
next($data);
}
if you just want a comma delimited list of keys from your array, regardless of their values, a combination of implode and array_keys might be a better approach
$string = implode(',', array_keys($data));
i got problem with my code and hopefully someone able to figure it out. The main purpose is to sort array based on its value (then reindex its numerical key).
i got this sample of filename :
$filename = array("index 198.php", "index 192.php", "index 144.php", "index 2.php", "index 1.php", "index 100.php", "index 111.php");
$alloutput = array(); //all of index in array
foreach ($filename as $name) {
preg_match('#(\d+)#', $name, $output); // take only the numerical from file name
array_shift($output); // cleaned. the last code create duplicate numerical in $output,
if (is_array($output)) {
$alloutput = array_merge($alloutput, $output);
}
}
//try to check the type of every value in array
foreach ($alloutput as $output) {
if (is_array($output)) {
echo "array true </br>";
} elseif (is_int($output)) {
echo "integer true </br>";
} elseif (is_string($output)) { //the numerical taken from filename always resuld "string".
echo "string true </br>";
}
}
the output of this code will be :
Array
(
[0] => 198
[1] => 192
[2] => 144
[3] => 2
[4] => 1
[5] => 100
[6] => 111
)
i have test every output in array. It's all string (and not numerical), So the question is how to change this string to integer, so i can sort it from the lowest into the highest number ?
the main purpose of this code is how to output array where it had been sort from lowest to highest ?
preg_match will keep the matched part in $outpu[1], so you can make use of that to convert the string to int and then add it to your alloutput array.
foreach ($filename as $name) {
preg_match('#(\d+)#', $name, $output);
$alloutput[] = intval($output[1]);
}
Use intval
$number_string = '14';
$number = intval('14');
With intval you can specify also the basis. If the number is decimal, hower, you can also use
$number = (int) $number_string;