I have created for code to check if its palindrome. Now if the string is not a palindrome I want it to be reversed.Can it be done using one conditional loop?
My php code:
class user{
public function __construct() {
if ($this->String_Rev()) {
echo 'Yes, palindrome';
} else {
echo 'not palindrome';
}
}
public function String_Rev() {
$str = "abba";
$i = 0;
while ($str[$i] == $str[strlen($str) - ($i + 1)]) {//Incrementing and decrementing the values in the string at the same time/
$i++;
if ($i > strlen($str)/ 2) {//If the i goes ahead of half of its string then return true and stop its execution.
return 1;
}
}
return 0;
}
}
$obj = new user();
Strings in PHP are not arrays, but you can select the character index of a string just like an array key, which makes the following possible:
<?php
$string = 'foobar';
$string_array = array();
//make an actual array of the characters first
//if you want this to be an object, do this part in your constructor,
//and assign this variable to an object property to work with.
for ($i=0; $i < strlen($string); $i++)
{
$string_array[$i] = $string[$i];
}
echo implode( $string_array ); //prints 'foobar'
echo '<br>' . PHP_EOL;
echo implode( array_reverse( $string_array ) ); //prints 'raboof'
You could easily simplify your palindrome logic by doing this:
//in your case, this would probably be it's own method,
//using the aforementioned class property made in the constructor
$is_palindrome = implode( $string_array ) === implode( array_reverse( $string_array ) );
Related
I am looking for a function or class that substitutes given string and returns array of all possible replacements.
In other words I am seeking for a magic_function:
function magic_function( $str, $find, $replace )
{
$arr = array();
// some magic stuff
return $arr;
}
var_dump( magic_function( 'aaa', 'a', 'b' ) );
/*
should return:
Array(
'aab',
'aba',
'baa',
'bba',
'bab',
'abb',
'bbb'
);
*/
I am thinking of using explode and then somehow looping through that array, but maybe there is a simpler way? Maybe with regex? Any ideas? :)
Thank you in advance!
explode and loop seems fairly simple.
<?php
function magic_function ($str, $find, $replace) {
$parts = explode($find, $str);
$n = count($parts)-1;
$p = 1<<$n;
for ($i=1; $i<$p; $i++) {
for ($perm="", $seps=$i, $j=0; $j<$n; $seps>>=1, $j++) {
$perm .= $parts[$j] . ($seps&1 ? $replace : $find);
}
$res[] = $perm . $parts[$n];
}
return $res;
}
Start from $i=0 to include the no-replacement case.
In PHP we can do things like these:
Class Example {
...
}
$example = 'Example';
$object = new $example();
Or the use of variable variables:
$hour = 18;
$greets = array('Good morning','Good afternoon','Good evening');
$values = array(13,21,23);//people is sleeping at 23PM, so they don't greet.
$n = count($values);
$greet = 'greets';
for($i=0;$i<$n;$i++){
if($hour < $values[$i]){
echo 'hello, '.${$greet}[$i];
break;
}
}
And others..
I wonder if it would be possible to access directly to a specific index of a multidimensional array in a similar way. Something like:
$array = array(...); //multidimensional array.
$position = '[0][4][3]';
print_r($array$position);
Thanks in advance.
UPDATE
I'm so sorry because I finished my question in a wrong way.
I need to set the multimesional array and add a value. i.e:
$array$position = $data;
You could implement it yourself with a custom function:
function getValueFromMultiDimensionalArray( array $array, string $key )
{
$keys = explode('][', $key);
$value = $array;
foreach ($keys as $theKey) {
// remove the opening or closing bracket if present
$theKey = str_replace([ '[', ']' ], '', $theKey);
if (!isset($value[$theKey])) {
return null;
}
$value = $value[$theKey];
}
return $value;
}
You can define path as dot separated , check the following solution
function getValueByKey($a,$p){
$c = $a;
foreach(explode('.',$p) as $v){
if(!array_key_exists($v, $c)) return null;
$c = $c[$v];
}
return $c;
}
You can use this function as
$path = '1.2.3.0';
$indexValue = getValueByKey($array, $path);
Nope, this is not possible.
The only thing you can do is to implement ArrayAccess interface, which allows to access instances with [] operator. But you will have to define the logic yourself.
class MyClass implements ArrayAccess
{
...
}
$x = new MyClass([0=>[4=>[3=>'hello world']]]);
$position = '[0][4][3]';
echo $x[$position]; //hello world
I'm trying to create a function to pick up words from a text file randomly, and no one here poblema. The problem arises when I try to verify if the user correctly inserts the words. Unfortunately, I always get a negative answer. From what I understood when called, the function can not save the contents into the variable that naturally remains empty.
<?php
function random_word() {
$dictionary = "dictionary.txt";
$word = file($dictionary);
$n = 0;
while ($n < 2) {
$n++;
$randomword = array_rand($word);
echo $word[$randomword];
}
}
$a = random_word();
echo "-----------------";
echo $a;
?>
If I try to check the $a variable it tells me that it is NULL. I'm sure the problem is the function but I know PHP shortly and I'm struggling to find the error.
You need to return something. Not sure if you want to return a string or an array but your code seems to be made for string.
<?php
function random_word() {
$dictionary = "dictionary.txt";
$word = file($dictionary);
$n = 0;
while ($n < 2) {
$n++;
$randomword = array_rand($word);
$returner .= $word[$randomword] . " ";
}
return trim($returner);
}
$a = random_word();
echo "-----------------";
echo $a;
?>
I have a class Tpl to mount template with this function (template.php)
function Set($var, $value){
$this->$var = $value;
}
A php file that call the function, example (form.php):
$t->Set("lbAddress","Address");
And a html file with the template with tags (template.html)
<tr><td>[lbAdress]</td></tr>
To print the html I have this function (template.php) - the notice points to this function
function Show_Temp($ident = ""){
// create array
$arr = file($this->file);
if( $ident == "" ){
$c = 0;
$len = count($arr);
while( $c < $len ){
$temp = str_replace("[", "$" . "this->", $arr[$c]);
$temp = str_replace("]", "", $temp);
$temp = addslashes($temp);
eval("\$x = \"$temp\";");
echo $x;
$c++;
}
} else {
$c = 0;
$len = count($arr);
$tag = "*=> " . $ident;
while( $c < $len ){
if( trim($arr[$c]) == $tag ){
$c++;
while( (substr(#$arr[$c], 0 ,3) != "*=>" ) && ($c < $len) ){
$temp = str_replace("[", "$" . "this->", $arr[$c]);
$temp = str_replace("]", "", $temp);
$temp = addslashes($temp);
eval("\$x= \"$temp\";"); //this is the line 200
echo $x;
$c++;
}
$c = $len;
}
$c++;
}
}
}
If the template .html have a line [lbName] and I don't have the line $t->Set("lbName","Name"); at the php code, I receive the error PHP Notice: Undefined property: Tpl::$lbName in ../template.php(200) : eval()'d code on line 1. The solution that I found is add lines like $t->Set("lbName","");, but if I have 50 tags in HTML that I don't use in PHP, I have to add all 50 $t->Set("tag_name","");. The error occurred after migrate to the PHP 5.
Can someone help me? Thanks
Perhaps a better way still would be not to rely on dynamic evaluation through eval (it's generally best to avoid eval where possible), but to replace [lbName] with the value stored in the object directly as and when needed. If you can replace [lbName] with $this->lbName, surely you can also replace it with the value of lBName that you've looked up on-the-fly?
To answer your original question, however:
If I understand correctly, you're setting the values like this:
$t->Set('foo', 'bar');
And – effectively – getting them like this:
$t->foo;
If so, you could implement a __get method to intercept the property references and provide your own logic for retrieving the value; e.g.:
public function __get($key)
{
// You can adapt this logic to suit your needs.
if (isset($this->$key))
{
return $this->$key;
}
else
{
return null;
}
}
In this case, you'd probably be better off using an associative array as the backing store, and then using __get and __set to access it; e.g.:
class Template
{
private $values = array();
public function __get($key)
{
if (array_key_exists[$key, $this->values])
{
return $this->values[$key];
}
else
{
return null;
}
}
public function __set($key, $value)
{
$this->values[$key] = $value;
}
}
How would you write a short php function to reverse a string. The function must:
have only one argument
not use the built-in function 'strrev' or 'array_reverse'
not a use a looping construct like 'for', 'foreach' or 'while'.
Quickly scanning down, these all look so long!
function rev($str) {
return $str?rev(substr($str,1)).$str[0]:'';
}
Recursive so obviously doesn't work on strings longer than 100 chars.
Since this sounds like homework question I'll tell you how but you code it yourself.
Turn the string into an array with a cast. Then use one of the array sorting functions that takes a user defined sorting function.
function reverseString($string) {
return shell_exec(sprintf('ruby -e \'puts "%s".reverse\'', preg_replace("/\"/", "\\\"", $string)));
}
Recursive solution:
function sr( $txt ){
return $txt[ strlen( $txt ) - 1 ] . ( ( strlen( $txt ) > 1 )?sr( substr( $txt, 0, strlen($txt)-1 ) ):null) ;
}
echo sr( "abc def ghi jklm" );
Explanation:
return $txt[ strlen( $txt ) - 1 ] // return last byte of string
. // concatenate it with:
(( strlen( $txt ) > 1 ) ? // if there are more bytes in string
sr( substr( $txt, 0, strlen( $txt ) - 1 ) // then with reversed string without last letter
: null ); // otherwise with null
To make it work with zero-length string, another conditional expression was added:
return (strlen($txt))? ($txt[ strlen( $txt ) - 1 ] . ( ( strlen( $txt ) > 1 )?sr( substr( $txt, 0, strlen($txt)-1 ) ):null)):"" ;
<?php
// Reversed string and Number
// For Example :
$str = "hello world. This is john duvey";
$number = 123456789;
$newStr = strrev($str);
$newBum = strrev($number);
echo $newStr;
echo "<br />";
echo $newBum;
OUTPUT :
first : yevud nhoj si sihT .dlrow olleh
second: 987654321`enter code here`
Meets all your requirements but works only in PHP 5.3 or higher. Making it work on others is left as homework.
function reverse($str) {
$i=0;
$j=strlen($str)-1;
start:
if($i>=$j) {
goto done;
}
$tmp = $str[$j];
$str[$j--] = $str[$i];
$str[$i++] = $tmp;
goto start;
done:
return $str;
}
function reverse_string($string) {
if($string !== '')
return substr($string, -1).reverse_string(substr($string, 0, strlen($string)-2));
}
A recursive solution. Feels like something like that is what your teacher is looking for.
function my_strrev ($str) {
$length = strlen($str);
switch ($length) {
case 0: return '';
case 1: return $str; break;
case 2: return $str[1] . $str[0];
default :
return $str[$length-1] . my_strrev(substr($str,1,-1)) . $str[0];
break;
}
}
It swaps the first and the last letter and than makes the same with the rest of the string.
Update:
Inspired by mateusza I created another solution (its fun ;))
function my_strrev2 ($str) {
return $str
? my_strrev2(substr($str, 1)) . $str[0]
: '';
}
It works similar to mateuszas, but this one appends the first character, instead of prepend the last one.
My answer is OOP and uses recursion. Takes care by itself of the recursion limit.
class StringReverser
{
public $reversed_string;
public function __construct ($string) {
$original_recursion_limit = ini_get('pcre.recursion_limit');
$array = str_split($string);
krsort($array);
$i = strlen($string);
ini_set('pcre.recursion_limit', $i+1);
$this->add2string($string, $i, $array);
ini_set('pcre.recursion_limit', $original_recursion_limit);
}
public function reverse() {
return $this->reversed_string;
}
private function add2string ($s, $i, $a) {
if($i) {
$i--;
$this->reversed_string .= $a[$i];
$this->add2string($s, $i,$a, $this->reversed_string);
}
}
}
$string = "Elzo Valugi";
echo $string ."<br>";
$reverser = new StringReverser($string);
echo $reverser->reverse();
<?php
$string="jomon is name my";
for($i=strlen($string);$i>=0;$i--)
{
$char.=$string{$i};
}
echo $char."<br/>";
for($i=0; $i<strlen($char);$i++)
{
if($char[$i+1]==" " || $char[$i+1]=="")
{
for($temp=$i; $temp>=0 && $char[$temp]!=' '; $temp--)
echo $char[$temp];
}
echo " ";
}
?>