How to save array variables in antoher array PHP - php

I am making question like 3 * 5 = ? and ? * 5 = 15. To make this, I will save an array variable ($arrayTotalQuestions) with the number 1 to 10 and an array variable ($arrayAnswers)
with the number 5,10,15,20,25,30,35,40,45,50 inside $array1. I will loop these 2 rows 20 times in my table like this:
foreach($array1 as $array1) {
echo $array1[array_rand($array1)];
}
The (array)variables inside the array:
$arrayTotalQuestions = range(1, 10);
$number = 5;
$arrayAnswers = (5, 10, 15, 20, 25, 30, 35, 40, 45, 50);
Now I want to store these 3 variables inside another array named $array1:
$array1 = array(
"<tr><td>$this->arrayTotalQuestions</td> <td>x</td> <td>$this->number</td> <td>=</td> <td><input type='text' name='txtAnswer[$this->arrayTotalQuestions]'></td></tr>",
"<tr><td><input type='text' name='txtAnswer[$this->arrayAnswers]' value=''></td> <td>x</td> <td>$this->number</td> <td>=</td> <td>$this->arrayAnswers</td></tr>"
);
But I am getting the error "array to string conversion...", because of the array variables inside $array1.
How can I solve this?

Like the error says you're trying to convert an array to a string, which isn't possible.
Take a look at this example:
<?php
$array = [1,2,3,4,5];
$newVar = "This is my array: $array";
?>
This results in the error E_NOTICE : type 8 -- Array to string conversion -- at line 3.
You're trying to output an array, which has multiple values in it, as part of your string. PHP doesn't know how you want to do this (should it just list all the array vars? Does it put a space between them? A comma? A comma and a space? etc)
So, instead, you need to convert the array into a string yourself. One way you can do this is to use the join() function in PHP.
join() takes 2 parameters: separator and array and outputs a string which is all the array values separated by your separator.
So the above example becomes:
<?php
$array = [1,2,3,4,5];
$newVar = "This is my array: ".join(", ", $array);
?>
Which outputs This is my array: 1, 2, 3, 4, 5
Updated based on comment
To use 2 or more arrays in the same foreach loop you just need to change it into a for loop:
for($i = 0, $i < count($array1); $i++) {
echo $array1[$i].': '.$array2[$i];
}
There is a way to do it with a foreach loop too, but I find that this isn't quite as clean a way to do this for maintenance (just my preference).
foreach($array1 as $index => $value) {
echo $value.': '.$array2[$index];
}

Related

php array numbers comparison

Let's say I have
$input = ['1, 2, 3, 4, 5'];
and I need to get every number in the array that are stored as a string. Is there any possible way to use foreach() or anything else for every number in that string? In other words to retrieve numbers from string.
Thanks in advance!
Use explode() to split the string into numbers.
foreach ($input as $numberstring) {
$numbers = explode(', ', $numberstring);
foreach ($numbers as $number) {
...
}
}
I have changed the input array, because quotes dont make sense in terns of the question, let me know if this is wrong.
$input = [1, 2, 3, '4', 5];
foreach($input as $i){
if(is_string($i)){//test if its a string
$strings[]=$i; //put stings in array (you could do what you like here
}
}
print_r($strings);
output:
Array
(
[0] => 4
)
your input is a single array element with one string of comma separated numbers
$input = ['1, 2, 3, 4, 5'];
For your example data, you could loop the array and check if the item from the array is a string using is_string. In your example the numbers are separated by a comma so you could use explode and use a comma as the separator.
Then you could use is_numeric to check the values from explode.
$input = ['1, 2, 3, 4, 5', 'test', 3, '100, a, test'];
foreach ($input as $item) {
if (is_string($item)) {
foreach (explode(',', $item) as $i) {
if (is_numeric($i)) {
echo trim($i) . "<br>";
}
}
}
}
Demo
That would result in:
1
2
3
4
5
100

How to create and fill a new associative array with values created in a for each?

I am a noob attempting to solve a program for a word search app I am doing. My goal is to take a string and compare how many times each letter of that string appears in another string. Then put that information into an array of key value pairs, where the key is each letter of the first string and the value is the number of times. Then order it with ar(sort) and finally echo out the value of the letter that appears the most (so the key with the highest value).
So it would be something like array('t' => 4, 'k' => '9', 'n' => 55), echo the value of 'n'. Thank you.
This is what I have so far that is incomplete.
<?php
$i = array();
$testString= "endlessstringofletters";
$testStringArray = str_split($testString);
$longerTestString= "alphabetalphabbebeetalp
habetalphabetbealphhabeabetalphabetalphabetalphbebe
abetalphabetalphabetbetabetalphabebetalphabetalphab
etalphtalptalphabetalphabetalbephabetalphabetbetetalphabet";
foreach ($testStringArray AS $test) {
$value = substr_count($longerTestString, $testStringArray );
/* Instead of the results of this echo, I want each $value to be matched with each member of the $testStringArray and stored in an array. */
echo $test. $value;
}
/* I tried something like this outside of the foreach and it didn't work as intended */
$i = array_combine($testStringArray , $value);
print_r($i);
If I understand correctly what you are after, then it's as simple as this:
<?php
$shorterString= "abc";
$longerString= "abccbaabaaacccb";
// Split the short sring into an array of its charachters
$stringCharachters = str_split($shorterString);
// Array to hold the results
$resultsArray = array();
// Loop through every charachter and get their number of occurences
foreach ($stringCharachters as $charachter) {
$resultsArray[$charachter] = substr_count($longerString,$charachter);
}
print_r($resultsArray);

comma separated string to array with key php

I have a string
$tailored_information="3, 5, 10, 13, 7, 6";
Now I have need to make an array like
$input_array = array("Id" => 3, "Id" => 5);
I am using this but not work cause i cant add key ID
explode(",", $tailored_information)
As been told, you can't have array with the same key, because it is a hash table, which will override the "id" every time.
I suggest you to use simply
explode(", ", $id_array);
or
explode(", ", $another_arr['id']);
like this you will group the data by id...
If you wish to go into some more complicated - you could create your own data structure, which will be non-unique array - where you will divide different values by key...
this way the print version will be whatever you want...
An array has to have unique keys. Also, you will now have spaces in your values
What you could do is explode by ", " and then take that array as your array straight away. If the key you want/need is always "Id" then it doesn't matter anyway.
<?php
$abc = "3, 5, 10, 13, 7, 6";
$new_array = explode(',',$abc);
$new_id_array = array();
foreach($new_array as $key=>$val){;
$new_id_array[$key]['id'] = $val;
}
print_r($new_id_array);
?>
you can not put same key in a array key. so for that you have to create a nested array.and that will solve ur problem and now you can have same array key, but in different arrays.OR
$abc = "3, 5, 10, 13, 7, 6";
$new_array = explode(',',$abc);
foreach($new_array as $key=>$val){
$new_id_array['id_'.$key] = $val;
}

PHP - counting an imploded array

I am trying to use sizeof or count to return the number of things inside the array, however whenever I use the $rank_ids2 to count rather than entering 1, 2, 3, 4, 67, 7 in manually, it just returns 1, but when I type them in the array directly, it counts 6 just fine!
$ranksAllowed = '|1|2|3|4|67|7|';
$rank_ids = explode('|', trim("|".$ranksAllowed."|", '|'));
$rank_ids2 = implode(", ", $rank_ids);
$arrayofallowed = array($rank_ids2);
echo sizeof($arrayofallowed);
$rank_ids is just turning the |1|2|.. format into 1, 2
My first solution to your problem would be to initially define $ranksAllowed as an array instead of a pipe-character-delimited string:
$ranksAllowed = array(1, 2, 3, 4, 67, 7);
This would make more sense in almost any foreseeable situation. If for some reason you'd rather keep $ranksAllowed as a string...
Some simplification
$rank_ids = explode('|', trim("|".$ranksAllowed."|", '|'));
can be simplified to:
$rank_ids = explode('|', trim($ranksAllowed, '|'));
Decide on string or array format
Right now it looks like you're trying to do 2 things at once (and achieving neither)
One possibility is you want to turn your pipe-delimited ("|1|2|3|...") string into a comma delimited string (like "1, 2, 3, ..."). In this case, you could simply do a string replace:
$commaDelimited = str_replace('|', ',', trim($ranksAllowed, '|'));
The other possibility (and I believe the one you're looking for) is to produce an array of all the allowable ranks, which you've already accomplished in an earlier step, but assigned to $rank_ids instead of $arrayofallowed:
$arrayofallowed = explode('|', trim($ranksAllowed, '|'));
//Should print out data in array-format, like you want
print_r($arrayofallowed);
//Echo the length of the array, should be 6
echo count($arrayofallowed);
implode converts an array to a string, so after everything you get this:
A string named $ranksAllowed that contains |1|2|3|4|67|7|
An array named $rank_ids that contains multiple elements, being them 1, 2, etc...
A string named $rank_ids2 that contains 1,2,3,4,67,7
An array named $arrayofallowed with only 1 element, being it the string inside $rank_ids2
To achieve a string that contains 1,2,3,4,67,7 from |1|2|3|4|67|7| you can just trim the | character as you do and replace | with ,. Is less CPU expensive.
$rank_ids2 = str_replace("|", ",", trim("|".$ranksAllowed."|", '|'));
If you want to count them you can explode it and count the elements:
$rank_ids2_array = explode(',', $rank_ids2);
echo sizeof($rank_ids2_array);
or with your code you can simply count the already exploded $rank_ids.
echo sizeof($rank_ids);
Try something like the following:
$ranksAllowed = '|1|2|3|4|5|67|7|';
$rank_ids = explode('|', trim($ranksAllowed, '|'));
echo count($rank_ids);
Just to explain the above, the $arrayofallowed is imploding the array of $rank_ids, creating a string. This will not give you the expected results when counted. If you simply count the $rank_ids (as explode() will leave you with an array), you should see the desired result of 7 items.
The $rank_ids is your array, and $arrayofallowed was a string.
Please see the sections of the PHP manual related to the implode() and explode() functions for more information.

change starting index when assigning one array to another in php

I am using str_split() to split a long strings into an array of length 16 each. And I'm assigning the returned array to one in my function. Like this:
$myarray = str_split($string, 16);
The problem is that I want the indexing of $myarray to start from a number other than 0, say 50. Currently I'm doing this:
foreach($myarray as $id => $value)
{
$myarray[$id + 50] = $value;
unset($myarray[$id]);
}
Is there a better solution? Because the arrays and strings I'm dealing with are very long. Thanks
You can use array_pad().
$myarray = str_split($string, 16);
$myarray = array_pad($myarray, -(size($myarray)+50), null);
It will fill the first 50 elements with nulls and push the rest of the array forward by 50 elements.

Categories