Engl12
Engl12

Reputation: 139

Use only part of a php variable - is this possible?

Is it possible to create a new variable with only the left X amount of values automatically?

I have a variable being passed to a page, but I need to use this in a query, both the full variable and part of it

full variable is like this - Day 55

Left of variable - Day

So consequently I would have two variables to use in a query

$var1 = "Day 55";

$var2 = "Day";

Sorry if this is a noob question, I'm new to php

Upvotes: 1

Views: 77

Answers (6)

Sajjad Mohammadadeh
Sajjad Mohammadadeh

Reputation: 21

Try substr and strpos:

$var1 = "Day 55";

$var2 = substr($var1, 0, strpos($var1, " "));

Upvotes: 0

Ahosan Karim Asik
Ahosan Karim Asik

Reputation: 3299

$var1 = "Day 55";
$tmp=explode(' ', $var1);

$var2=$tmp[0];
$var3=$tmp[1]

//outpu:

$var1="Day 55";
$var2="Day";
$var3="55"

Upvotes: 0

oopbase
oopbase

Reputation: 11405

The easiest way would be using the explode function:

$arr = explode(" ", $var1);

Now the $arr variable contains the values "Day" and "55".

To get the variable "Day", you simply access the array at [0].

$var2 = $arr[0];

Upvotes: 0

Sougata Bose
Sougata Bose

Reputation: 31749

Try with explode();

$var = explode(' ', $yourString);

Upvotes: 0

Aleksandar Vasić
Aleksandar Vasić

Reputation: 593

If your variables are always like Day 55 Day 35 Day 7 then use explode()

http://php.net/manual/en/function.explode.php

$day = explode(' ',$var1);

you will get array:

$day[0] //Day
$day[1] //55

Upvotes: 1

nl-x
nl-x

Reputation: 11832

What you want to use is the substring.

$var1 = "Day 55";
$var2 = substr($var1,0,3); // 3 characters of $var1, starting with character 0.

Upvotes: 1

Related Questions