Echo only if it hasn't already been echoed? - php

What I'm trying to do is make a list of entries from a form, but I do not want the same entry to be displayed multiple times in the list if it was entered more than once in the form. For example, say one person enters "1" but then two people enter "2", I would only want the 2 to appear once in the list. What function would I be able to use for this?

The best way should be to store all your entries in an array (basic numerical indexed array) and then, remove duplicate with
uniqueEntries = array_unique($yourEntries);
The documentation : array_unique
example of code:
$entries = array();
$entries[] = 1;
$entries[] = 1;
$entries[] = 2;
$entries = array_unique($entries);
print_r($entries);
will output:
Array
(
[0] => 1
[2] => 2
)

In this case you should use PHP Arrays. Arrays are 2-dimensional tables.
/* Array
* key => value
* #key personID
* #value optionValue
*/
$array = array(
1 => 1, // Person 1 chose Option 1
2 => 2, // Person 2 chose Option 2
3 => 2 // Person 3 chose Option 2
);
print_r($array);
Prints
Array
(
[1] => 1
[2] => 2
[3] => 2
)
You are now able to fetch a set of unique values by accessing the array via array_unique($array);.
$array_unique = array_unique($array);
$array_unique_values = array_values($array_unique);
// Access array values directly and store into variables.
// Notice that arrays in PHP start with the index zero.
$option1 = $array_unique_values[0];
$option2 = $array_unique_values[1];
echo "Option #1: " . $option1 . "\n";
echo "Option #2: " . $option2;
Prints
Option #1: 1
Option #2: 2
Voilà.

You have no built-in function for that in PHP. But you could try with something like:
$echoList = array();
function echoOnce( $text )
{
global $echoList;
if(!in_array($text, $echoList)) {
echo $text;
$echoList[] = $text;
}
}
And then just use echoOnce( "whatever" ) instead of echo "whatever"

Related

How to decode an array?

I have this PHP array
$gender = array (
0 => array('Male','m.gif'),
1 => array('Female','f.gif'),
2 => array('Other','o.gif'),
);
And this ODBC
$DB = $core_db->Execute("SELECT ID, Name, Age, Location, Gender FROM Profiles
ORDER BY Name");
I want to use echo' . decode_gender($DB->fields[4], '2') . '; But I don't know how to make this decode function to connect that $DB->fields[4] is the same Gender from the array $gender in order to use it.
This function should do what you want. It takes the Gender value from the table lookup to index into the $genders array, and the second parameter to decide which value from the lookup array to return. Note that since you've said you want a value of 2 to return the second value in the array, you have to subtract one from the $idx value:
function decode_gender($gender, $idx) {
$genders = array (
0 => array('Male','m.gif'),
1 => array('Female','f.gif'),
2 => array('Other','o.gif'),
);
return $genders[$gender][$idx-1];
}
echo decode_gender(2, 2) . PHP_EOL;
echo decode_gender(1, 1) . PHP_EOL;
Output:
o.gif
Female
Demo on 3v4l.org

How can I efficiently search a field for flipped word order?

I have the following array.
$arr = array('foo','bar','foo-bar','abc','def','abc-def','ghi','abc-def-ghi');
I'm given a new string to decide to add to the array or not. If the string is already in the array, don't add it. If it is not in the array in its current form, but in a flipped word form is found, don't add it.
How should I accomplish this?
Examples:
'foo' —-> N - Do NOT add, already found
'xyz' —-> Y - Add, this is new
'bar-foo' —-> N - Do NOT add, already found in the flipped form 'foo-bar'
'ghi-jkl' —-> Y - Add, this is new
What do you recommend?
If you want to exclude items whose elements ('abc','ghi', etc.) are contained in another order and not only reversed, you could do:
$arr = array('foo','bar','foo-bar','abc','def','abc-def','ghi','abc-def-ghi');
function split_and_sort($str) {
$partsA = explode('-', $str);
sort($partsA);
return $partsA;
}
$arr_parts = array_map('split_and_sort', $arr);
$tests = array('foo','xyz','bar-foo','ghi-jkl');
$tests_parts = array_map('split_and_sort', $tests);
foreach($tests_parts as $test) {
if( !in_array($test, $arr_parts)) {
echo "adding: " . join('-', $test) . "\n";
$arr[] = join('-', $test);
}
else {
echo "skipping: " . join('-', $test) . "\n";
}
}
var_export($arr);
which outputs:
skipping: foo
adding: xyz
skipping: bar-foo
adding: ghi-jkl
array (
0 => 'foo',
1 => 'bar',
2 => 'foo-bar',
3 => 'abc',
4 => 'def',
5 => 'abc-def',
6 => 'ghi',
7 => 'abc-def-ghi',
8 => 'xyz',
9 => 'ghi-jkl',
)
Heres a suggestions on one way you can try...
for each string in $arr, reverse it as push into another array called $rev_arr
then...
$new_array = array();
foreach ($arr as $arr_1) $new_array[$arr_1] = true; // just set something
foreach ($rev_arr as $arr_2) $new_array[$arr_2] = true; // do also for reverse
now you can check what you want to do based on
if ( isset($new_arr[ $YOUR_TEST_VARIABLE_HERE ]) ) { // match found
}

PHP - Use everything from 1st array, remove duplicates from 2nd?

I have 2 arrays - the first one is output first in full. The 2nd one may have some values that were already used/output with the first array. I want to "clean up" the 2nd array so that I can output its data without worrying about showing duplicates. Just to be sure I have the terminology right & don't have some sort of "array within an array", this is how I access each one:
1st Array
$firstResponse = $sth->fetchAll();
foreach ($firstResponse as $firstResponseItem) {
echo $firstResponseItem['samecolumnname']; // Don't care if it's in 2nd array
}
2nd Array
while( $secondResponseRow = $dbRequest->fetch_assoc() ){
$secondResponseArray = array($secondResponseRow);
foreach ($secondResponseArray as $secondResponseItem){
echo $secondResponseItem['samecolumnname']; //This can't match anything above
}
}
Thanks!
For example:
$response_names = array();
$firstResponse = $sth->fetchAll();
foreach ($firstResponse as $firstResponseItem)
$response_names[] = $firstResponseItem['samecolumnname'];
while( $secondResponseRow = $dbRequest->fetch_assoc() ){
$secondResponseArray = array($secondResponseRow);
foreach ($secondResponseArray as $secondResponseItem) {
if (!in_array($secondResponseItem['samecolumnname'], $response_names))
$response_names[] = $secondResponseItem['samecolumnname'];
}
}
array_walk($response_names, function($value) { echo $value . '<br />' });
If I understand what you're looking to do and the arrays are in the same scope, this should work.
$secondResponseArray = array($secondResponseRow);
$secondResponseArray = array_diff($secondResponseArray, $firstResponse);
//secondResponseArray now contains only unique items
foreach ($secondResponseArray as $secondResponseItem){
echo $secondResponseItem['samecolumnname'];
}
If you know that the keys of duplicate values will be the same you could use array_diff_assoc to get the items of the first array that aren't in the other supplied arrays.
This code
<?php
$a = array('abc', 'def', 'ghi', 'adg');
$b = array('abc', 'hfs', 'toast', 'adgi');
$r = array_diff_assoc($b, $a);
print_r($a);
print_r($r);
produces the following output
[kernel#~]php so_1.php
Array
(
[0] => abc
[1] => def
[2] => ghi
[3] => adg
)
Array
(
[1] => hfs
[2] => toast
[3] => adgi
)
[kernel#~]

Split A String at X, then at Y Value

I have the following code:
$Field = $FW->Encrypt("Test");
echo "<pre>";
print_r($Field);
echo "</pre>";
# $IV_Count = strlen($Field['IV']);
# $Key_Count = strlen($Field['Key']);
# $Cipher_Count = strlen($Field['CipheredText']);
foreach ($Field AS $Keys => $Values){
echo $Keys."Count = ".strlen($Values)."<br><br>";
}
The output is as:
Array
(
[CipheredText] => x2nelnArnS1e2MTjOrq+wd9BxT6Ouxksz67yVdynKGI=
[IV] => 16
[Key] => III#TcTf‡eB12T
)
CipheredTextCount = 44
IVCount = 2
KeyCount = 16
The IV/KeyCount is always returning the same value regardless of the input. But the CipheredTextCount changes depending on the input.. For example:
$Field = $FW->Encrypt("This is a longer string");
The foreach loop returns:
CipheredTextCount = 64
IVCount = 2
KeyCount = 16
and now for my question. Lets take the first example with the TextCount of 44
How can I split a string after implode("",$Field); to display as the original array? an example would be:
echo implode("",$Field);
Which outputs:
ijGglH/vysf52J5aoTaDVHy4oavEBK4mZTrAL3lZMTI=16III#TcTf‡eB12T
Based on the results from the strlen?
It is possible to store the count of the first $Cipher_Count in a database for a reference
My current setup involves storing the key and IV in a seperate column away from the ciphered text string.. I need this contained within one field and the script handles the required information to do the following:
Retrieve The long string > Split string to the original array > Push
array to another function > decrypt > return decoded string.
Why not use serialize instead? Then when you get the data out of the database, you can use unserialize to restore it to an array.
$Combined_Field = implode("",$Field);
echo $str1 = substr($Combined_Field, 0, $Cipher_Count)."<br><br>";
echo $str2 = substr($Combined_Field,$Cipher_Count,$IV_Count)."<br><br>";
echo $str3 = substr($Combined_Field, $IV_Count+$Cipher_Count,$Key_Count);
Or use a function:
function Cipher_Split($Cipher, $Cipher_Count, $KeyCount, $IVCount){
return array(
"Ciphered Text" => substr($Cipher,0,$Cipher_Count),
"IV" => substr($Cipher,$Cipher_Count,$IVCount),
"Key" => substr($Cipher,$IVCount+$Cipher_Count,$KeyCount)
);
}

Cleanest way of working out next variable name based on sequential order?

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
}

Categories