0

In the following code, I'm trying to create an array or a string based on if type is true or false. If type were true, then i need to create an array else I need to keep things as a string. I was trying as below, but it does not seem to work. Can you help?

<?php
$type = True;

if($type){
    $body = "body['body']"; //Start an array
} else {
    $body = 'body'; //Just a string
}

$body  = 'Hello'; //$body = the value from up there

print_r($body);
?>

Expected Results:

If type = true //Array
print_r($body);
Array ([body] => Hello)

If type = false //String
print_r($body); 
Hello

Edit The content for the array or string is outside the if and comes after it. I need to start as a array or sting based on the type.

1
  • 3
    Whatever executes inside the if - else statement is pretty useless here .. because you are just overwriting it with $body = 'Hello' after the end of the if-else Commented Jan 6, 2014 at 6:32

4 Answers 4

3
$type  = true;
$value = 'Hello';

if($type){
    $body['body'] = $value;
} else {
    $body = $value;
}

print_r($body);
Sign up to request clarification or add additional context in comments.

3 Comments

The content for the array or string is outside the if.
I forgot to add, the content is set after the if. Which is why I posted that way.
$value needs to be assigned inside the if to ensure the type of $body is as expected.
0

Try this.

$x = array('body'=>'Hello');
if($type){
    $body = $x;
} else {
    $body = 'body';
}

2 Comments

The content for the array or string is outside the if
check it now - this should be fine.
0

You can write it on one line with shorthand if.

$body = ($type ? array('body'=>'Hello') : 'Hello');

var_dump($body);

Comments

0
$type  = true;
$value = 'Hello';

if($type){
    $body['body'] = $value;
} else {
    $body = $value;
}
if (is_array($body)) {
// content for array goes here
} else {
// content for string goes here
}
print_r($body);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.