How to use explode function in PHP without delimeters - php

i have one variable like this :
$variable = "0904201600000123";
i want to make the first 8 digits become like this :
2016-04-09
have tried to use this code :
<?php
$name = "$variable;
$explode = explode("", $name);
echo $explode[0];
echo "-";
echo $explode[1];
echo "-";
echo $explode[2];
?>
but it does not work.
May you know where is the problem?
Thank you so much for your help.

You can access a variable as you can access an array, if you were to echo:
$string = "test";
echo $string[0];
It would echo t, and onwards.
You could concat the string and make a new variable like:
$v = "0904201600000123";
$date = $v[0].$v[1].'-'.$v[2].$v[3].'-'.$v[4].$v[5].$v[6].$v[7];
echo $date;
I tested it on my local machine and it worked
Note: If you want to use the method using the explode function as I saw you did earlier, you could use the str_split function which will instead make the result an array.

Substr() can break a string in parts.
$FirtsPart = Substr($variable, 0, 8);
$SecondPart = Substr($variable, 8, 8);
$FirstPart = strtotime('Y-m-d', $FirstPart);
$variable = $FirstPart . $SecondPart;

$variable = "0904201600000123";
preg_match("/([0-9]){2}([0-9]){2}([0-9]){4}/", $variable, $datematches);
$newdate = $datematches[3] . "-" . $datematches[2] . "-" . $datematches[1];
Chances are I've more than likely massively over complicated that. Not tested but should do the trick.

$variable = "0904201600000123";
Note: The date format of $variable didnt understand. If its not a standard format, considering it as a string and separate using substr
Option 1
$date = substr($variable, 0, 2).'-'.substr($variable, 2, 2).'-'.substr($variable, 4, 4);
echo $date;
Option 2
$dd = substr($variable, 0, 2);
$mm = substr($variable, 2, 2);
$yy = substr($variable, 4, 4);
$date = $dd.'-'.$mm.'-'.$yy;
echo $date;

Related

Explode PHP : Converting id-name to name-id to id-name

I need some help. I have "name" and "id", I've display is as "id"-"name" (suggestion) I have a function that convert it to "name-id" (displayed in textbox after picking the suggestion).
The problem is, how can I properly explode if the name = Backlink-Spider and id = 25, the result
will be 25-Backlink-Spider and converted it to Backlink-Spider-25 . I tend to return it to unconverted , the result is Spider-25-Backlink.
This is my code.
$xpldName = explode("-", $posted['name'], 2);
$cdata = $C->loadByName($xpldName[1]);
$_POST['name'] = $xpldName[1]."-".$xpldName[0];
Explode the whole string.
Implode all the strings except the last one
Print last string - imploded string
Demo Code(Not tested):
$xpldName = explode("-", $posted['name'], 2);
$name = array_slice($xpldName, 0, -1);
$name = implode("-", $name);
$id = end($xpldName);
echo $id . " " . $name;

How to use implode function manualy?

My array contain date $a1[0] day $a1[1] month $a1[2] year I want the result as year/day/month give me one solution.
Below is my code
<?php
$a1 = array("01","10","2012");
$result = implode("/",$a1);
print $result;
?>
This will print 01/10/2012 but I want this result 2012/01/10. How can I take the array manualy using implode function?
How can I take year first day second and month third?
You can't use implode alone for that matter, if you are having exactly this pattern (elements order are inverted) the use this code (YYYY/MM/DD):
$a1 = array("01", "10", "2012");
$result = implode("/", array_reverse($a1));
print $result;
Else use a regex (YYYY/MM/DD):
$a1 = array("01", "10", "2012");
$result = preg_replace('/(\d{2})\/(\d{2})\/(\d{4})/', '$3/$2/$1', implode("/", $a1));
print $result;
If you need the format of (YYYY/DD/MM) then use this one:
$a1 = array("01", "10", "2012");
$result = preg_replace('/(\d{2})\/(\d{2})\/(\d{4})/', '$3/$1/$2', implode("/", $a1));
print $result;
You can use array_reverse like this:
$result = implode("/", array_reverse($a1));
This will create a new array in the reverse order.
Use the mktime function. If you have a $timestamp, you can format is as you like with the date function:
$timestamp = mktime(0, 0, 0, $a1[1], $a1[0], $a1[2]);
echo date('y/m/d', $timestamp);
You can also use a loop (manual implode):
$a1 = array("01","10","2012");
$a1_length = sizeof($a1);
$date = '';
for ($i = $a1_length; $i > 0; $i--) {
$date .= $a1[$i] . '/';
}
$date = rtrim($date, '/');
echo $date;

Dissecting a string

I suspect that this has been asked before, but I have no idea what it's actually called, so I couldn't find anything.
I am creating a browser based game in which the player has a 10x10 grid. Each grid square has a few aspects to it, some as binary flags and other as hex values.
To store this information in an array, I want a given cell to contain the following:
"9A0101" where 9A is the tile type, and the 0s and 1s are binary flags about that map tile.
I want to be able to take "9A0101" and split it into "9A", "0", "1", "0", and "1" as separate variables.
TLDR:
How do I slice up a string in PHP? The string will always be the same length, and the parts where I want to cut it will always be at the same offsets.
use substr() to get the parts of string
<?php
echo substr('9A0101', 0,2); // 9A
echo substr('9A0101', 2, 1); // 0
echo substr('9A0101', 3, 1); // 1
echo substr('9A0101', 4, 1); // 0
echo substr('9A0101', 5, 1); // 1
?>
what about substr() ? :
<?php
$str = '9A0101';
echo substr($str,0,2);
echo substr($str,2,1);
echo substr($str,3,1);
echo substr($str,4,1);
echo substr($str,5,1);
?>
You can the substr() function
<?php
$str = "9A0101";
$arr = Array();
$arr[0] = substr($str, -6, 2);
$arr[1] = substr($str, -4, 1);
$arr[2] = substr($str, -3, 1);
$arr[3] = substr($str, -2, 1);
$arr[4] = substr($str, -1, 1);
foreach($arr as $key => $val) {
echo($key . "=>" . $val . '<br/>');
}
?>
Or maybe can use the str_split() function.
$str = "9A0101";
//splitting the string
$array = str_split($str, 2);
var_dump($array);
If you are looking for a single function call, regex can serve you well.
preg_split('~(^..|.)\K~', $string);
The above will split the string on the zero-width position after the first two characters of the string or each subsequent character. \K means forget what is already matched.
If you want to save the 5 values as individual variables, then you can use list() or array destructuring syntax. Demo
[$type, $one, $two, $three, $four] = preg_split('~(^..|.)\K~', $string);
If you wish, you can even access the single byte characters by their string offset. Demo
$type = $string[0] . $string[1];
$one = $string[2];
$two = $string[3];
$three = $string[4];
$four = $string[5];

How to explode date like 09.06.2010 and get the "2010" with php?

How to explode date into pieces and get last part from it. Lets say, we have 09.06.2010 and we wanna get "2010" from it.How to do it with php?
Try this method:
end( explode( '.', $date ) );
OR
date( 'Y', strtotime( $date ) );
$sDate = "09.06.2010";
$aDate = explode(".", $sDate);
$iYear = $aDate[2];
var_dump($iYear);
There are other methods, like parsing the date. But you asked:
$date_output = explode('.', $date_input);
$date_output = $date_output[2];
You mean like 4 last digits of such string?
substr("09.06.2010",-4);
Although just like Pekka says in his comment, doing actual date processing will make your code more robust and easier to change in future.
if you always want the last position, you can try with strrpos(), it will find the last occurrence of a given character. So you may do:
$string = '11.22.3456';
$pos = strrpos($string, '.');
$year = ($pos !== false) ? substr($string, $pos + 1) : 'N/a';
var_dump($year);
explode() is always an option, just wanted to give another one.
$timestamp = time();
list($dd, $mm, $yy) = explode('.', strftime('%d.%m.%Y', $timestamp));
echo $mm;
See: strftime
See: list
function dateExp($date, $sign=null, $argIndex = '0'){
$exp = null;
if(!empty($date) && !empty($sign)){
$exp = explode($sign, $date);
} else {
$exp = explode('/', $date);
}
if($argIndex!=='0'){
$exp = $exp[$argIndex];
}
return $exp;
}
$setDate = '2015-10-20';
$date1 = dateExp($setDate,'-');
print '<pre>';
print_r($date1);
print_r($date1[0]);
Output:
Array
(
[0] => 2015
[1] => 10
[2] => 20
)
2015

Converting an integer to a string in PHP

Is there a way to convert an integer to a string in PHP?
You can use the strval() function to convert a number to a string.
From a maintenance perspective its obvious what you are trying to do rather than some of the other more esoteric answers. Of course, it depends on your context.
$var = 5;
// Inline variable parsing
echo "I'd like {$var} waffles"; // = I'd like 5 waffles
// String concatenation
echo "I'd like ".$var." waffles"; // I'd like 5 waffles
// The two examples above have the same end value...
// ... And so do the two below
// Explicit cast
$items = (string)$var; // $items === "5";
// Function call
$items = strval($var); // $items === "5";
There's many ways to do this.
Two examples:
$str = (string) $int;
$str = "$int";
See the PHP Manual on Types Juggling for more.
$foo = 5;
$foo = $foo . "";
Now $foo is a string.
But, you may want to get used to casting. As casting is the proper way to accomplish something of that sort:
$foo = 5;
$foo = (string)$foo;
Another way is to encapsulate in quotes:
$foo = 5;
$foo = "$foo"
There are a number of ways to "convert" an integer to a string in PHP.
The traditional computer science way would be to cast the variable as a string:
$int = 5;
$int_as_string = (string) $int;
echo $int . ' is a '. gettype($int) . "\n";
echo $int_as_string . ' is a ' . gettype($int_as_string) . "\n";
You could also take advantage of PHP's implicit type conversion and string interpolation:
$int = 5;
echo $int . ' is a '. gettype($int) . "\n";
$int_as_string = "$int";
echo $int_as_string . ' is a ' . gettype($int_as_string) . "\n";
$string_int = $int.'';
echo $int_as_string . ' is a ' . gettype($int_as_string) . "\n";
Finally, similar to the above, any function that accepts and returns a string could be used to convert and integer. Consider the following:
$int = 5;
echo $int . ' is a '. gettype($int) . "\n";
$int_as_string = trim($int);
echo $int_as_string . ' is a ' . gettype($int_as_string) . "\n";
I wouldn't recommend the final option, but I've seen code in the wild that relied on this behavior, so thought I'd pass it along.
Use:
$intValue = 1;
$string = sprintf('%d', $intValue);
Or it could be:
$string = (string)$intValue;
Or:
settype($intValue, 'string');
Warning: the below answer is based on the wrong premise. Casting 0 number to string always returns string "0", making the code provided redundant.
All these answers are great, but they all return you an empty string if the value is zero.
Try the following:
$v = 0;
$s = (string)$v ? (string)$v : "0";
There are many possible conversion ways:
$input => 123
sprintf('%d',$input) => 123
(string)$input => 123
strval($input) => 123
settype($input, "string") => 123
You can either use the period operator and concatenate a string to it (and it will be type casted to a string):
$integer = 93;
$stringedInt = $integer . "";
Or, more correctly, you can just type cast the integer to a string:
$integer = 93;
$stringedInt = (string) $integer;
As the answers here demonstrates nicely, yes, there are several ways. However, in PHP you rarely actually need to do that. The "dogmatic way" to write PHP is to rely on the language's loose typing system, which will transparently coerce the type as needed. For integer values, this is usually without trouble. You should be very careful with floating point values, though.
I would say it depends on the context. strval() or the casting operator (string) could be used. However, in most cases PHP will decide what's good for you if, for example, you use it with echo or printf...
One small note: die() needs a string and won't show any int :)
$amount = 2351.25;
$str_amount = "2351.25";
$strCorrectAmount = "$amount";
echo gettype($strCorrectAmount); //string
So the echo will be return string.
My situation :
echo strval("12"); => 12
echo strval("0"); => "0"
I'm working ...
$a = "12";
$b = "0";
echo $a * 1; => 12
echo $b * 1; => 0
I tried all the methods above yet I got "array to string conversion" error when I embedded the value in another string. If you have the same problem with me try the implode() function.
example:
$integer = 0;
$id = implode($integer);
$text = "Your user ID is: ".$id ;
You can simply use the following:
$intVal = 5;
$strVal = trim($intVal);
$integer = 93;
$stringedInt = $integer.'';
is faster than
$integer = 93;
$stringedInt = $integer."";

Categories