Create array through function - php

Is there any way to return an array, something like:
$array = [
"parcela" => "1",
"valor" => "100",
];
Using the function below? I need to return an array with the number of plots and the value:
Function PHP
function calcParcelaJuros($valor_total,$parcelas,$juros=0) {
if($juros==0) {
$string = 'PARCELA - VALOR <br />';
for($i=1;$i<($parcelas+1);$i++) {
$string .= $i.'x (Sem Juros) - R$.number_format($valor_total/$parcelas, 2, ",", ".").' <br />';
}
return $string;
} else {
$string = 'PARCELA - VALOR <br />';
for($i=1;$i<($parcelas+1);$i++) {
$I =$juros/100.00;
$valor_parcela = $valor_total*$I*pow((1+$I),$parcelas)/(pow((1+$I),$parcelas)-1);
$string .= $i.'x (Juros de: '.$juros.'%) - R$ '.number_format($valor_parcela, 2, ",", ".").' <br />';
}
return $string;
}
}
print(calcParcelaJuros(250,4,2));

You only have to save the data on the array, properly formatted as you need, the use the return statement and you are good to go.
You can see, that php's return statement can return values even by reference, as it is explained here; check the second example, it will help you.
But for the sake of giving you a fast example, you can do whatever you need inside the function:
function calcParcelaJuros($valor_total,$parcelas,$juros=0) {
$parcelas = array();
if($juros==0) {
for($i=1;$i<($parcelas+1);$i++) {
...
...
$parcelas[] = ["parcela" => "1", "valor" => "100"]
}
return $parcelas;
} else {
...
...
}
}
You can make any process you require, save the info in the array, then return it.

Related

Return string value of random values from multidimensional array using recursion function

I'm stuck with the following problem. I need to generate a sentence based on word and phrase values from JSON string. Some parts of sentence may be random selection based on values, provided in array.
Example JSON:
$json = '{"s1": [
"I like fruit ",
[
"banana",
"plums",
"strawberry"
],
"and vegetable "
[
"tomato",
"carrot",
"potato"
]
]
}';
Final string may be "I like fruit banana and vegetable carrot". I'll have several similar JSONs to combine a paragraph.
My code:
$data = json_decode($json, true);
print_recursive($data, $data);
function print_recursive($arr, $parent_arr) {
foreach ($arr as $val) {
if (is_array($val)) {
if(check_strings_in_array($val)){
$str .= $val[rand(0, count($val) - 1)].' ';
}
print_recursive($val, $val);
} else {
if(count($parent_arr)>0){
if(!check_strings_in_array($parent_arr)){
$str .= $val . " ";
}
}
}
}
echo $str;
//// return $str - need to return a value, not echo
};
function check_strings_in_array($arr)
{
return array_sum(array_map('is_string', $arr)) == count($arr);
}
I can't figure out how to assign a print_recursive() result to a variable for later use. If I write:
$final = print_recursive($data, $data);
It shows empty value. I tried "return print_recursive($val, $val)" or "return $val", but it doesn't give desired result.
Can anyone help me figure this out?
You could use a reference to a store (variable), which receives the result of your recursive function.
Following logic:
<?php
$store = ''; // the result store
print_recursive($data, $data, $store);
var_dump($store); // string(47) "I like fruit strawberry and vegetable carrot "
function print_recursive($arr, $parent_arr, &$str) { // added a store reference: &$str
foreach ($arr as $val) {
if (is_array($val)) {
if(check_strings_in_array($val)){
$str .= $val[rand(0, count($val) - 1)].' ';
}
print_recursive($val, $val, $str); // added $str
} else {
if(count($parent_arr)>0){
if(!check_strings_in_array($parent_arr)){
$str .= $val . " ";
}
}
}
}
}
working demo
EDIT:
How to return the result
If you'd also like the result $str returned from the recursive function, just use: return $str before the closing function brace }.
This working demo shows how you can get the returned $str from your recursive function - we store it in $result.

php loop, func_get_arg(0)

can somone explain me how this code works
<?php
function append($initial)
{
$result=func_get_arg(0);
foreach(func_get_arg()as $key=>value){
if($key>=1)
{
$result .=' '.$value;
}
}
return $result;
echo append('Alex,'James','Garrett');
?>
why do we have a 0 at the func_get_arg(0), and this is a loop there are 0,1,2 shouldn't it only post Alex, James?
and what is the (as) does the func_get_arg() as $key => value. give the array the names to the value ?
this is basic but a bit messy!
That's how it works:
<?php
function append($initial)
{
// Get the first argument - func_get_arg gets any argument of the function
$result=func_get_arg(0);
// Get the remaining arguments and concat them in a string
foreach(func_get_args() as $key=>value) {
// Ignore the first (0) argument, that is already in the string
if($key>=1)
{
$result .=' '.$value;
}
}
// Return it
return $result;
}
// Call the function
echo append('Alex,'James','Garrett');
?>
This function will do the same that:
echo implode(' ', array('Alex', 'James', 'Garrett'));
before you used the foreach{} loop. You have returned 'Alex' which is at position 0.
$result=func_get_arg(0);
foreach(){
}
return $result; //It returns Alex
//foreach() loop
foreach(func_get_arg()as $key=>value){
/*Its looping and only printing after
the key gets to 1 and then the loop goes to 2.Eg: $result[$key]=> $value; */
if($key>=1)
{
$result .=' '.$value;
}
}

PHP array check if value in specific key exists

I am using PHP 5.5.12.
I have the following multidimensional array:
[
{
"id": 1,
"type":"elephant",
"title":"Title of elephant"
},
{
"id": 2,
"type":"tiger",
"title":"Title of tiger"
},
{
"id": 3,
"type":"lion",
"title":"Title of lion",
"children":[{
"id": 4,
"type":"cow",
"title":"Title of cow"
},
{
"type":"elephant",
"title":"Title of elephant"
},
{
"type":"buffalo",
"title":"Title of buffalo"
}]
}
]
I am iterating this array using foreach loop.
The array key type must be in elephant, tiger and lion. If not, then the result should return false.
How can I achieve this?
So you want to check if your $myArray contains a value or not:
// first get all types as an array
$type = array_column($myArray, "type");
// specify allowed types values
$allowed_types = ["lion", "elephant", "tiger"];
$count = count($type);
$illegal = false;
// for loop is better
for($i = 0; $i < $count; $i++)
{
// if current type value is not an element of allowed types
// array, then both set the $illegal flag as true and break the
// loop
if(!in_array($type[$i], $allowed_types)
$illegal = true;
break;
}
Since you're using PHP5.5.12, you can make use of array_column.
$arr = json_decode($json, true);
//Walk through each element, only paying attention to type
array_walk( array_column($arr, 'type'), function($element, $k) use(&$arr) {
$arr[$k]['valid_type'] = in_array($element, array('lion', 'tiger', 'elephant'));
});
From here, each element in the array ($arr) will have a new key valid_type with a boolean value - 1 if the type is valid, 0 if it isn't.
https://eval.in/350322
Is this something that you are looking for?
foreach($your_array as $item) {
if (!array_key_exists('type', $item)) {
return FALSE;
}
}
function keyExists($arr, $key) {
$flag = true;
foreach($arr as $v) {
if(!isset($v[$key])) {
$flag = false;
break;
}
}
return $flag;
}
Hope this helps :)

PHP Function that can return value from an array key a dynamic number of levels deep

Using PHP, I would like to write a function that accomplishes what is shown by this pseudo code:
function return_value($input_string='array:subArray:arrayKey')
{
$segments = explode(':',$input_string);
$array_depth = count(segments) - 1;
//Now the bit I'm not sure about
//I need to dynamically generate X number of square brackets to get the value
//So that I'm left with the below:
return $array[$subArray][$arrayKey];
}
Is the above possible? I'd really appreciate some pointer on how to acheive it.
You can use a recursive function (or its iterative equivalent since it's tail recursion):
function return_value($array, $input_string) {
$segments = explode(':',$input_string);
// Can we go next step?
if (!array_key_exists($segments[0], $array)) {
return false; // cannot exist
}
// Yes, do so.
$nextlevel = $array[$segments[0]];
if (!is_array($nextlevel)) {
if (1 == count($segments)) {
// Found!
return $nextlevel;
}
// We can return $nextlevel, which is an array. Or an error.
return false;
}
array_shift($segments);
$nextsegments = implode(':', $segments);
// We can also use tail recursion here, enclosing the whole kit and kaboodle
// into a loop until $segments is empty.
return return_value($nextlevel, $nextsegments);
}
Passing one object
Let's say we want this to be an API and pass only a single string (please remember that HTTP has some method limitation in this, and you may need to POST the string instead of GET).
The string would need to contain both the array data and the "key" location. It's best if we send first the key and then the array:
function decodeJSONblob($input) {
// Step 1: extract the key address. We do this is a dirty way,
// exploiting the fact that a serialized array starts with
// a:<NUMBEROFITEMS>:{ and there will be no "{" in the key address.
$n = strpos($input, ':{');
$items = explode(':', substr($input, 0, $n));
// The last two items of $items will be "a" and "NUMBEROFITEMS"
$ni = array_pop($items);
if ("a" != ($a = array_pop($items))) {
die("Something strange at offset $n, expecting 'a', found {$a}");
}
$array = unserialize("a:{$ni}:".substr($input, $n+1));
while (!empty($items)) {
$key = array_shift($items);
if (!array_key_exists($key, $array)) {
// there is not this item in the array.
}
if (!is_array($array[$key])) {
// Error.
}
$array = $array[$key];
}
return $array;
}
$arr = array(
0 => array(
'hello' => array(
'joe','jack',
array('jill')
)));
print decodeJSONblob("0:hello:1:" . serialize($arr));
print decodeJSONblob("0:hello:2:0" . serialize($arr));
returns
jack
jill
while asking for 0:hello:2: would get you an array { 0: 'jill' }.
you could use recursion and array_key_exists to walk down to the level of said key.
function get_array_element($key, $array)
{
if(stripos(($key,':') !== FALSE) {
$currentKey = substr($key,0,stripos($key,':'));
$remainingKeys = substr($key,stripos($key,':')+1);
if(array_key_exists($currentKey,$array)) {
return ($remainingKeys,$array[$currentKey]);
}
else {
// handle error
return null;
}
}
elseif(array_key_exists($key,$array)) {
return $array[$key];
}
else {
//handle error
return null;
}
}
Use a recursive function like the following or a loop using references to array keys
<?php
function lookup($array,$lookup){
if(!is_array($lookup)){
$lookup=explode(":",$lookup);
}
$key = array_shift($lookup);
if(!isset($array[$key])){
//throw exception if key is not found so false values can also be looked up
throw new Exception("Key does not exist");
}else{
$val = $array[$key];
if(count($lookup)){
return lookup($val,$lookup);
}
return $val;
}
}
$config = array(
'db'=>array(
'host'=>'localhost',
'user'=>'user',
'pass'=>'pass'
),
'data'=>array(
'test1'=>'test1',
'test2'=>array(
'nested'=>'foo'
)
)
);
echo "Host: ".lookup($config,'db:host')."\n";
echo "User: ".lookup($config,'db:user')."\n";
echo "More levels: ".lookup($config,'data:test2:nested')."\n";
Output:
Host: localhost
User: user
More levels: foo

How to search text using php if ($text contains "World")

How to search text using php?
Something like:
<?php
$text = "Hello World!";
if ($text contains "World") {
echo "True";
}
?>
Except replacing if ($text contains "World") { with a working condition.
In your case you can just use strpos(), or stripos() for case insensitive search:
if (stripos($text, "world") !== false) {
echo "True";
}
What you need is strstr()(or stristr(), like LucaB pointed out). Use it like this:
if(strstr($text, "world")) {/* do stuff */}
If you are looking an algorithm to rank search results based on relevance of multiple words here comes a quick and easy way of generating search results with PHP only.
Implementation of the vector space model in PHP
function get_corpus_index($corpus = array(), $separator=' ') {
$dictionary = array();
$doc_count = array();
foreach($corpus as $doc_id => $doc) {
$terms = explode($separator, $doc);
$doc_count[$doc_id] = count($terms);
// tf–idf, short for term frequency–inverse document frequency,
// according to wikipedia is a numerical statistic that is intended to reflect
// how important a word is to a document in a corpus
foreach($terms as $term) {
if(!isset($dictionary[$term])) {
$dictionary[$term] = array('document_frequency' => 0, 'postings' => array());
}
if(!isset($dictionary[$term]['postings'][$doc_id])) {
$dictionary[$term]['document_frequency']++;
$dictionary[$term]['postings'][$doc_id] = array('term_frequency' => 0);
}
$dictionary[$term]['postings'][$doc_id]['term_frequency']++;
}
//from http://phpir.com/simple-search-the-vector-space-model/
}
return array('doc_count' => $doc_count, 'dictionary' => $dictionary);
}
function get_similar_documents($query='', $corpus=array(), $separator=' '){
$similar_documents=array();
if($query!=''&&!empty($corpus)){
$words=explode($separator,$query);
$corpus=get_corpus_index($corpus);
$doc_count=count($corpus['doc_count']);
foreach($words as $word) {
$entry = $corpus['dictionary'][$word];
foreach($entry['postings'] as $doc_id => $posting) {
//get term frequency–inverse document frequency
$score=$posting['term_frequency'] * log($doc_count + 1 / $entry['document_frequency'] + 1, 2);
if(isset($similar_documents[$doc_id])){
$similar_documents[$doc_id]+=$score;
}
else{
$similar_documents[$doc_id]=$score;
}
}
}
// length normalise
foreach($similar_documents as $doc_id => $score) {
$similar_documents[$doc_id] = $score/$corpus['doc_count'][$doc_id];
}
// sort fro high to low
arsort($similar_documents);
}
return $similar_documents;
}
IN YOUR CASE
$query = 'world';
$corpus = array(
1 => 'hello world',
);
$match_results=get_similar_documents($query,$corpus);
echo '<pre>';
print_r($match_results);
echo '</pre>';
RESULTS
Array
(
[1] => 0.79248125036058
)
MATCHING MULTIPLE WORDS AGAINST MULTIPLE PHRASES
$query = 'hello world';
$corpus = array(
1 => 'hello world how are you today?',
2 => 'how do you do world',
3 => 'hello, here you are! how are you? Are we done yet?'
);
$match_results=get_similar_documents($query,$corpus);
echo '<pre>';
print_r($match_results);
echo '</pre>';
RESULTS
Array
(
[1] => 0.74864218272161
[2] => 0.43398500028846
)
from How do I check if a string contains a specific word in PHP?
This might be what you are looking for:
<?php
$text = 'This is a Simple text.';
// this echoes "is is a Simple text." because 'i' is matched first
echo strpbrk($text, 'mi');
// this echoes "Simple text." because chars are case sensitive
echo strpbrk($text, 'S');
?>
Is it?
Or maybe this:
<?php
$mystring = 'abc';
$findme   = 'a';
$pos = strpos($mystring, $findme);
// Note our use of ===.  Simply == would not work as expected
// because the position of 'a' was the 0th (first) character.
if ($pos === false) {
    echo "The string '$findme' was not found in the string '$mystring'";
} else {
    echo "The string '$findme' was found in the string '$mystring'";
    echo " and exists at position $pos";
}
?>
Or even this
<?php
$email = 'name#example.com';
$domain = strstr($email, '#');
echo $domain; // prints #example.com
$user = strstr($email, '#', true); // As of PHP 5.3.0
echo $user; // prints name
?>
You can read all about them in the documentation here:
http://php.net/manual/en/book.strings.php
in my opinion strstr() is better than strpos(). because strstr() is compatible with both PHP 4 AND PHP 5. but strpos() is only compatible with PHP 5. please note that part of servers have no PHP 5
/* https://ideone.com/saBPIe */
function search($search, $string) {
$pos = strpos($string, $search);
if ($pos === false) {
return "not found";
} else {
return "found in " . $pos;
}
}
echo search("world", "hello world");
Embed PHP online:
body, html, iframe {
width: 100% ;
height: 100% ;
overflow: hidden ;
}
<iframe src="https://ideone.com/saBPIe" ></iframe>
The best solution is my method:
In my method, only full words are detected,But in other ways it is not.
for example:
$text='hello world!';
if(strpos($text, 'wor') === FALSE) {
echo '"wor" not found in string';
}
Result: strpos returned true!!! but in my method return false.
My method:
public function searchInLine($txt,$word){
$txt=strtolower($txt);
$word=strtolower($word);
$word_length=strlen($word);
$string_length=strlen($txt);
if(strpos($txt,$word)!==false){
$indx=strpos($txt,$word);
$last_word=$indx+$word_length;
if($indx==0){
if(strpos($txt,$word." ")!==false){
return true;
}
if(strpos($txt,$word.".")!==false){
return true;
}
if(strpos($txt,$word.",")!==false){
return true;
}
if(strpos($txt,$word."?")!==false){
return true;
}
if(strpos($txt,$word."!")!==false){
return true;
}
}else if($last_word==$string_length){
if(strpos($txt," ".$word)!==false){
return true;
}
if(strpos($txt,".".$word)!==false){
return true;
}
if(strpos($txt,",".$word)!==false){
return true;
}
if(strpos($txt,"?".$word)!==false){
return true;
}
if(strpos($txt,"!".$word)!==false){
return true;
}
}else{
if(strpos($txt," ".$word." ")!==false){
return true;
}
if(strpos($txt," ".$word.".")!==false){
return true;
}
if(strpos($txt," ".$word.",")!==false){
return true;
}
if(strpos($txt," ".$word."!")!==false){
return true;
}
if(strpos($txt," ".$word."?")!==false){
return true;
}
}
}
return false;
}

Categories