I want to echo out the content of this array in a 1, 2 way
$arr = array("name", "john", "lastname", "doe", "age", "55");
so I wish for it to look like
name = john
lastname = doe
age = 55
And my code currently looks like this
for ($x=0;$x<count($arr)/2;$x++) {
echo $arr[$x] . " = " . $arr[$x++];
}
But it does not work. The 2 elements of the variable have to be outputted within the same going through of the loop so I can't just concatenate them or something like that.
Your array should look like this :
$arr = array("name"=> "john", "lastname"=> "doe", "age"=> 55);
and then you can go like this :
foreach ($arr as $key => $val) {
echo $key , " = " , $val ;
}
It just needs a couple of small adjustments:
for ($x = 0; $x < count($arr); $x+=2) {
echo $arr[$x] . " = " . $arr[$x+1] . "<br/>";
}
Change the loop criteria so it'll get all the way to the end of the dataset.
Change the loop criteria so it'll increment $x 2 steps at a time, and ten just get the +1 for the
According to your question, it appears you want a line break between each data item. If this is for a web application, use <br/>. If it's for command-line or text-based output, use PHP_EOL.
However, there are other possible approaches using foreach which might be considered more elegant, as shown in the other answers here.
BTW, if you could have a more structured array using associative key-value pairs insteading of relying on index patterns e.g. array("name" => "john", "lastname" => "doe", "age" => 55); that would make your life easier in general, so if you have the freedom to make a change like that, I'd advise it.
Related
I have a search input in my wordpress site, which I want to display different placeholdes each time the page been refreshed. So I will have an array of the different values, the function that will loop randomly through the array, and I think my problem is with the result. I'm using a plugin for the search input, so to define for example that the placeholder would say 'hello', I need to do:
$item['textinput']= "hello";
So I need the result to be:
$item['textinput']= $placeholders;
I am adding the whole code:
$placeholders = array("yo i hio", "and him", "nayo jones");
function randominputs($input){
$i=1;
while($i<=20){
$randNum = rand(1,100);
if($input==$i){
$item['textinput']= $placeholders;
}
$i++;
}
}
Thanks
Use array_rand:
$placeholder = $placeholders[array_rand($placeholders)];
I would suggest adding the sizeof() call to your code.
For example if I wanted to call a random result from an array you could try...
$arr = array("1", "2", "3", "4", "5", "6", "7");
$len = sizeof($arr) - 1; // account for the 0 position
$rand = rand(0,$len);
echo $arr[$rand];
You can also use like:
$placeholders = array("yo i hio", "and him", "nayo jones");
$randomPlaceholder = array_rand($placeholders);
$item["textinput"] = $randomPlaceholder[0];
I've PHP array something like this
$array = array("foo", "bar", "hallo", "world", "fooo", "bar1", "hall_o", "wor1ld", "foo", "bard", "hzallo", "w44orld");
I want to compare each element of an array with remaining elements.
Ex: I want to compre "foo" with "bar", "hallo", "world", "fooo", "bar1", "hall_o", "wor1ld", "foo", "bard", "hzallo" and "w44orld".
Then, I want to compre "bar" with "foo", "hallo", "world", "fooo", "bar1", "hall_o", "wor1ld", "foo", "bard", "hzallo", "w44orld"
and so on till last element.
Let's consider element, which we are comparing as $var_1 and variable for remaining elements as $var_2;
If similar_text($var_1, $var_2, $percent); returns $percent value > 90% then I want to print
$var_1 and all corresponding similar text values of $var_2 for which matching percentage > 90
Currently I'm planning to use two loops to achieve this, external loop for $var_1 and internal loop for $var_2 .
Each element of the array can have value upto 5000 characters and there can be 1000 elements in a array, so my current logic is very expensive.
Any direction to handle it in better way?
In order for the indexing to work, the array $arr must have unique values:
$arr = array("foo", "bar", "hallo", "world", "fooo", "bar1", "hall_o", "wor1ld", "bard", "hzallo", "w44orld");
$dexed = array();
foreach ($arr as $key => $value){
$dexed[$key]['val'] = $value;
$dexed[$key]['key'] = $key;
}
$out = array();//output
$rev = array();//reverse lookup array
$t = 80;//threshold value
$cnt = count($dexed);
$k = 0;
for ($i=0; $i<$cnt-1; $i++){
for ($j=$i+1; $j<$cnt; $j++){
//similar_text calculates differently depending on order of arguments
similar_text($dexed[$i]['val'], $dexed[$j]['val'], $percent1);
similar_text($dexed[$j]['val'], $dexed[$i]['val'], $percent2);
if (($percent1 >= $t) || ($percent2 >= $t)){
//check if value already exists under different key
if (in_array($dexed[$i]['val'], array_keys($rev))){
if ( ! in_array($dexed[$j]['val'], array_keys($rev))){
$fkey = $rev[$dexed[$i]['val']];//key found
$next = count($out[$fkey]);
$out[$fkey][$next]['val'] = $dexed[$j]['val'];
$out[$fkey][$next]['key'] = $dexed[$j]['key'];
$rev[$dexed[$j]['val']] = $fkey;
}
} else {
$out[$k][0]['val'] = $dexed[$i]['val'];
$out[$k][0]['key'] = $dexed[$i]['key'];
$out[$k][1]['val'] = $dexed[$j]['val'];
$out[$k][1]['key'] = $dexed[$j]['key'];
$rev[$dexed[$i]['val']] = $k;
$rev[$dexed[$j]['val']] = $k;
$k++;
}
}
}
}
Once $out is generated, use the following to generate an index array:
$index = array();
foreach ($out as $key => $group){
$cnt = count($group);
foreach ($group as $key2 => $word){
for ($i=0; $i<$cnt; $i++){
if ($i != $key2){
$index[$word['key']][] = $key.':'.$i;
}
}
}
}
Access all similar words for a given key (the key value for the word in the original array $arr);
$key = 2;
foreach ($index[$key] as $value){
$parts = explode(':', $value);
echo '<p>'.$out[$parts[0]][$parts[1]]['val'].'</p>';
}
Unfortunately, what you're proposing is slow if the list gets bigger than trivial and won't work very well. Here's something that might, and will also be algorithmically efficient.
First, create an inverted index of letter bigrams (http://en.wikipedia.org/wiki/Bigram). For example (assuming case insensitivity):
"foo" => ^f,fo,oo,o$
"hzallo" => ^h,hz,za,al,ll,o$
You can use an underscore instead of ^ and $, which are pseudocharacters. I think they'll help you rank the results.
Now to find similar words you can use a typical ranking algorithm (see tf*idf and simpler token-count-based algorithms) to rank the best matches. So, given "hallo,"
QUERY(^h,ha,al,ll,lo,o$) AGAINST index_of_words
& you'll get a good match for "hzallo" because ^h,al,ll,lo,o$ all match.
You'll need something like Solr or your database's TEXT index to do this unless you want to write a simple inverted index, but it's worth it. The lookup will be orders of magnitude faster than what you're entertaining, and the results will be ranked by closeness.
Afterwards, you can use something like levenshtein, but I don't think you'll need to in many cases.
I have an array of temperature data by hour. Some hours have zero data instead of a temp. When graphing using Google Charts, the zero causes the line graph to plummet. My temporary fix was to replace the zero values with null, causing a break in the line graph. The ideal solution would be to take the values on either side of the zero, and average them. The array is in order by hour. Help?
$array = array(
"1AM" => "65",
"2AM" => "66",
"3AM" => "68",
"4AM" => "68",
"5AM" => "68",
"6AM" => "0",
"7AM" => "70",
"8AM" => "71",
"9AM" => "71",
"10AM" => "73",
);
Here's my script replacing the 0's with nulls:
$array = array ();
foreach($parsed_json->history->observations as $key => $value) {
$temp = (int)$value->tempi;
if ($temp==0) {
str_replace(0, null, $temp);
}
$hour = $value->date->hour;
$array[$hour] = $temp;
};
This Example would work great if the data was mine, but alas, it's from a JSON feed.
Would I use an array_walk() sort of deal? How would I reference the current place in the array? Any help is appreciated!
I would scratch out the null portion, and just foreach-loop through the final array.
So, change your current code to:
$array = array ();
foreach($parsed_json->history->observations as $key => $value) {
$temp = (int)$value->tempi;
}
$hour = $value->date->hour;
$array[$hour] = $temp;
And add this below it:
foreach($array as $hour => $temp){
if($temp == "0"){
$numHour = $hour[0];
$hourPlus = ($numHour + 1) . "AM";
$hourMinus = ($numHour - 1) . "AM";
$valuePlus = $array[$hourPlus];
$valueMinus = $array[$hourMinus];
$average = ($valuePlus + $valueMinus)/2;
$array[$hour] = $average;
}
}
?>
This of course assumes that the values on either side of the zero are also not zero. You may want to add a check for that somewhere in there.
Tested and proven method.
Couldn't you do something along the lines of:
str_replace(0, ((($key-1)+($key+1))/2), $temp);
Where $key is array position, take the value before 0 and after 0 add them and divide them by 2 to get the average.
I'll let you sort out what happens if first, last or consecutive values are 0.
$the_keys=array_keys($array);
foreach($the_key as $index=>$key)
{
if($array[$key]==0)
{
$array[$key]=($array[$the_key[$index-1]]+$array[$the_key[$index+1]]/2);
}
}
How can I change the code below so each part is added together in a little bunch instead of smushed together? If a little part that appears on the screen is 123, it should add 12+3 and display 15 instead of 123. I have tried sum_array and other things but it won't work to add PARTS with other PARTS in little bunches. I can only get it to display smushed together results how it is below, or add the wrong parts or the whole thing other ways.
$data = mysql_query('SELECT weight FROM my_table WHERE session_id = "' . session_id() . '"');
$params = array();
while ($row = mysql_fetch_assoc($data)) {
$params[] = $row['weight'];
}
$combinations=getCombinations($params);
function getCombinations($array)
{
$length=sizeof($array);
$combocount=pow(2,$length);
for ($i=1; $i<$combocount; $i++)
{
$binary = str_pad(decbin($i), $length, "0", STR_PAD_LEFT);
$combination='';
for($j=0;$j<$length;$j++)
{
if($binary[$j]=="1")
$combination.=$array[$j];
}
$combinationsarray[]=$combination;
echo $combination . "<br>";
}
return $combinationsarray;
}
It looks like
$combination.=$array[$j];
is your problem . in PHP is used for String Concatenation and not math. Because PHP is a loosely data typed language you are telling PHP to take the String value of $array[$j] and ".=" (append) it to $combination giving you the 12 .= 3 == "123" problem and not 15 like what you want. You should try += instead.
If I understand what you're trying to do, I think you want to use addition + instead of concatination . in the following line:
if($binary[$j]=="1")
$combination += $array[$j];
Hope my title explains it ok! Here's more detail:
I'm creating an array which stores keys & their values. Eg.
test1 = hello
test2 = world
test3 = foo
What is the cleanest way of working out what to call the next key? Let's say I will know the first part is 'test', but I don't know what the highest value number is. Obviously in this case I want it to be called 'test4'.
In the example below I want the next key to be 'test46', as it is the next highest value:
test6 = blah
test45 = boo
test23 = far
This sounds like you should be using an array with numerical indexes instead.
You could however use some code like this...
$arr = array('test6', 'test45', 'test23');
$max = 0;
foreach($arr as $value) {
$number = filter_var($value, FILTER_SANITIZE_NUMBER_INT);
$max = max($max, $number);
}
$newKey = 'test' . ++$max; // string(6) "test46"
CodePad.
Implementation of #alex answer without using a loop:
$arr = array('test6', 'test45', 'test23');
$max = max(filter_var_array($arr, FILTER_SANITIZE_NUMBER_INT));
$newKey = 'test' . ++$max; // string(6) "test46"
CodePad
This data structure would be better stored as an array.
$test = array();
$test[] = 'hello';
$test[] = 'world';
$test[] = 'foo';
You then don't need to know the highest number to add a new item, just use the empty brackets syntax (shown above) to add an item to the end of the array.
You then have access to a wealth of array functions that PHP gives you to work with your data: http://php.net/manual/en/ref.array.php
When you want to get item 43 from the array, use:
echo $test[42];
Arrays are counted from 0 rather than 1, so item 43 will have an index of 42.
What are you using that for? If numbering the array is a must-have, just use a simple numerical indexed array instead, and simply prepend the key with "test" if you need it to show up as "test1":
<?php
$array = array(
6 => 'blah',
45 => 'boo',
23 => 'bar'
);
$array[] = 'new';
echo $array[46] . "\n"; // this is 'new'
foreach( $array as $key => $value ) {
echo "test$key = $value<br />\n"; // test6 = blah
}