PHP calling out index positions in an array [duplicate] - php

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;
}

Related

Calling index number location using PHP

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);
}

PHP: Creating an associative array programmatically

I have a return string from a 3rd party plugin that looks like a var_dump from an array. I'm trying to parse into a valid associative array. Looking at various examples and doing some tests with the code that follows. The last segment demonstrates the problem I'm having. I'm trying to parse out the data into a string and then programmatically create an array after my data string has been finished. When I do a print_r on $vegetables2, I get:
Array([0] => “Gourd”=”40 kilojoules”,”Artichoke”=”105 kilojoules”,”Cassava”=”550 kilojoules”)
And the echo $vegetables2["Artichoke"] produces no value. Can someone please guide me at the correct syntax to create the array equivalent to the first two examples?
//this works:
echo "From creating the entire array with a static string:<br/>";
$vegetables = array("Gourd"=>"40 kilojoules", "Artichoke"=>"105 kilojoules", "Cassava"=>"550 kilojoules");
echo "Artichoke: " . $vegetables["Artichoke"] . "<br/>";
//this works too
$vegetables1['Gourd'] = "40 kilojoules";
$vegetables1['Artichoke'] = "105 kilojoules";
$vegetables1['Cassava'] = "550 kilojoules";
echo "From creating one element at a time:<br/>";
echo "Artichoke: " . $vegetables1["Artichoke"] . "<br/>";
//this doesn't work
$strData = "\"Gourd\"=\"40 kilojoules\",";
$strData = $strData . "\"Artichoke\"=\"105 kilojoules\",";
$strData = $strData . "\"Cassava\"=\"550 kilojoules\"";
echo $strData ."<br/>";
$vegetables2 = array($strData);
print_r($vegetables2);
echo "Artichoke: " . $vegetables2["Artichoke"];
$strData = "\"Gourd\"=\"40 kilojoules\",";
$strData = $strData . "\"Artichoke\"=\"105 kilojoules\",";
$strData = $strData . "\"Cassava\"=\"550 kilojoules\"";
$dd=str_replace('"','',"$strData");
$ff=explode(',',$dd);
foreach ($ff as $c)
{
$xx=explode('=',$c);
$vegetables2["$xx[0]"]=$xx[1];
}
print_r($vegetables2);
echo "Artichoke: " . $vegetables2["Artichoke"];
This string is your input:
"Array ( [Gourd] => 40 kilojoules [Artichoke] => 105 kilojoules [Casava] => 550 kilojoules )"
use strpos() to locate "("
use strpos() to locate ")"
use substr() to get what is between ( and )
use explode to divide the result wherever "[" appears
use array() to start a new array
use foreach to reformat each piece
use explode to divide each piece wherever "=>" appears
use trim to remove excess characters (left and right)
use $data[$key] = $value to create a new array to your liking

PHP array not extracting as expected - why is this?

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";
}

Php array in a foreach loop

I have been trying to create a Multidimensional array from an already existing array. The reason I am doing this is so I can separate the super array into a more categorized version so that later on I can run foreach on just those categories in another script.
This is a snippet of code // Please read comments :)
$and = array();
if($this-> input-> post('and')) // This is the super array and[] from a previous input field
{
if(preg_grep("/reason_/", $this-> input-> post('and'))) // Search for the reason_
{
foreach($this-> input-> post('and') as $value) // if reason_ is present
{
$and['reason_and'] .= end(explode('_', $value)) . ' , '; // Remove everything before and including _ so then i would get only values like 1, 2, 3, 4, and then concatenate them to the index
}
}
if(preg_grep("/status_/", $this-> input-> post('and'))) // Search for status
{
foreach($this-> input-> post('and') as $value) // If it is in the super array
{
$and['status_and'] .= end(explode('_', $value)) . ' , '; // Remove everything before and including _ so then I would get values again like 1,2,3,4,5 and then concatenate them to the index
}
}
}
This approach is not giving me expected outcome however, I am getting a big string like so :
array(2) { ["reason_and"]=> string(24) "2 , 3 , 4 , 3 , 4 , 5 , "
["status_and"]=> string(24) "2 , 3 , 4 , 3 , 4 , 5 , "
So to my knowledge (which is limited) when I try to do a foreach over the array
[reason_and]
I only get one loop since the array ["reason_and] only has one value (the 24 character string?). Is it possible to have the reason_and have a value for each of the numbers?
Is this even possible? I'm quite confused.
I've referred to this question for reference but I still do not get a outcome that I can work with. Thanks in advance.
This
$and['reason_and'] .= end(explode('_', $value)) . ' , ';
^^^^----
should be
$and['reason_and'][] = end(explode('_', $value)) . ' , ';
^^--
which turns it into an "array push" operation, not a string concatenation. Then 'reason_and' will be an array, and you foreach over it.
first of all preg_grep returns an array with matched values, so
$andArray = $this-> input-> post('and'); // This is the super array and[] from a previous input field
if($andArray) {
$reason = preg_grep("/reason_/", $andArray); // Search for the reason_
if($reason) { // if reason_ is present
foreach($reason as $value) {
$and['reason_and'] .= end(explode('_', $value)) . ' , '; // Remove everything before and including _ so then i would get only values like 1, 2, 3, 4, and then concatenate them to the index
}
}
$status = preg_grep("/status_/", $andArray); // Search for status
if($status) {
foreach($status as $value){ // If it is in the super array
$and['status_and'] .= end(explode('_', $value)) . ' , '; // Remove everything before and including _ so then I would get values again like 1,2,3,4,5 and then concatenate them to the index
}
}
}
Or if you need result as array, then remove ' , ' and replace dot with [];

PHP in_array() can't even match a single character. Strict is set to true

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';
}
}

Categories