How could I switch from an array? - php

I'm trying to route set of array, but it's not working.
<?php
$routes = array('home'=>'Home Page','about'=>'About Me');
$action = isset($_GET['action']) ? $_GET['action'] : '';
switch($action) {
foreach($routes as $key => $value) {
case $key:
echo $value;
break;
}
}
But instead, it returns Parse error: syntax error, unexpected token "foreach", expecting "case" or "default" or "}"

Try to solve it this way, with using filter_input on get variable:
<?php
$routes = array('home'=>'Home Page','about'=>'About Me');
$action = filter_input(INPUT_GET, 'action');
if ($action) {
echo $routes[$action];
}

I don't think you can do that, even if you could, I would advise against it as it is not a conventional practice.
Why not just use something like the following?
<?php
$routes = array('home'=>'Home Page','about'=>'About Me');
$action = isset($_GET['action']) ? $_GET['action'] : '';
if (array_key_exists($action, $routes)) {
echo $routes[$action];
} else {
// Do you error handling here.
}

Related

Get variable from link in PHP, issue

I have URL below:
session.php?action=create_program
Then I have the following piece of code:
if( isset($_GET['action']) ){ $action= $_GET['action']; $action=''; }
It returns an empty string while it should return ''create_program'
I think you were trying to set it to empty if you didn't receive anything in your get request. So either do it like this
if( isset($_GET['action']) ){
$action= $_GET['action'];
} else {
$action='';
}
Or, even simpler, give a default value that remains set if the get parameter is absent.
$action = '';
if( isset($_GET['action']) ){
$action= $_GET['action'];
}
Finally, as suggested by Cashbee in the comment below, you can use the ternary operator to check whether $_GET['action'] was set and, in case it's not, give a default value to $action.
$action = isset($_GET['action']) ? $_GET['action'] : '';
Easy is the use of the ternary operator like this:
$action = isset($_GET['action']) ? $_GET['action'] : '';
You should always check if the variable is set or empty.
$action = empty($_GET['action']) ? '' : $_GET['action'];
Or even better, use the PHP filter functions.
$action = filter_input(INPUT_GET, 'action');
This has the advantage, you can even use rules, to give the appropriate result, like described in http://php.net/manual/de/function.filter-input.php
You are setting $action to empty at last that's why it is returning an empty string
if( isset($_GET['action']) )
{
$action= $_GET['action'];
// $action=''; //Just remove this code
}
//$action will be empty if not have $_GET['action'];, just for PHP7
$action = $_GET['action'] ?? '';
hope can help you!

Is it possible to use a Switch Case to set a different output?

I've figured out how to do this. I've passed the location name as a 3rd argument from the show_data_inline_location back on location.php back to the function by including the location name as follows:
show_data_inline_city($data['Cars_In_Location'], 'car', $data['Name']);
Then in the function itself I have done added the following argument:
function show_data_inline_location($data, $type, $location_name)
And added this to create a URL friendly string:
$loc_name = strtolower(str_ireplace(" ","-", $location_name));
Then echoing this:
echo '<a href="'.$link_url.$name.'-in-'.$loc_name.'"><div class="overlay">'.PHP_EOL;
This way I don't need to seperate the case in the switch, only need to use this for the difference between 'car' and 'location':
if ($type == 'car') { echo 'this'; }
if ($type == 'location') { 'that'; }
Thanks for all of your help.
If in your $data array there is one car and one location then you can do the following to save the variables and use them later:
$loc_name = '';
$car_name = '';
foreach ($data as $key => $value) {
if ( is_special_car($value['name']) )
continue;
switch ($type) {
case 'car':
$car_name = $name;
break;
case 'location':
$loc_name = $name;
break;
default:
break;
}
if($loc_name && $car_name){
//You have a car and loc name now
}
}
If your $data array is different you will have to modify the code of course, maybe resetting the $loc_name and $car_name when you've done whatever you needed to after getting them.
I've figured out how to do this. I've passed the location name as a 3rd argument from the show_data_inline_location back on location.php back to the function by including the location name as follows:
show_data_inline_city($data['Cars_In_Location'], 'car', $data['Name']);
Then in the function itself I have done added the following argument:
function show_data_inline_location($data, $type, $location_name)
And added this to create a URL friendly string:
$loc_name = strtolower(str_ireplace(" ","-", $location_name));
Then echoing this:
echo '<a href="'.$link_url.$name.'-in-'.$loc_name.'"><div class="overlay">'.PHP_EOL;
This way I don't need to seperate the case in the switch, only need to use this for the difference between 'car' and 'location':
if ($type == 'car') { echo 'this'; }
if ($type == 'location') { 'that'; }
Thanks for all of your help.

Two " Array to string conversion" notices (Prestashop)

I'm not so sure whether it is smart to post both problems in one question, but lets try:
So, I was checking my server's error log and it still has two notices, both about "Array to string conversion in [...]".
The first line should be this:
$replace = $route['keywords'][$key]['prepend'].$params[$key].$route['keywords'][$key]['append'];
Context:
// Build an url which match a route
if ($this->use_routes || $force_routes) {
$url = $route['rule'];
$add_param = array();
foreach ($params as $key => $value) {
if (!isset($route['keywords'][$key])) {
if (!isset($this->default_routes[$route_id]['keywords'][$key])) {
$add_param[$key] = $value;
}
} else {
if ($params[$key]) {
$replace = $route['keywords'][$key]['prepend'].$params[$key].$route['keywords'][$key]['append'];
} else {
$replace = '';
}
$url = preg_replace('#\{([^{}]*:)?'.$key.'(:[^{}]*)?\}#', $replace, $url);
}
}
$url = preg_replace('#\{([^{}]*:)?[a-z0-9_]+?(:[^{}]*)?\}#', '', $url);
if (count($add_param)) {
$url .= '?'.http_build_query($add_param, '', '&');
}
}
The second one is this line:
$uri_path = __PS_BASE_URI__.$id_image.($type ? '-'.$type : '').$theme.'/'.$name.'.jpg';
as part of this:
// legacy mode or default image
$theme = ((Shop::isFeatureActive() && file_exists(_PS_PROD_IMG_DIR_.$ids.($type ? '-'.$type : '').'-'.(int)Context::getContext()->shop->id_theme.'.jpg')) ? '-'.Context::getContext()->shop->id_theme : '');
if ((Configuration::get('PS_LEGACY_IMAGES')
&& (file_exists(_PS_PROD_IMG_DIR_.$ids.($type ? '-'.$type : '').$theme.'.jpg')))
|| ($not_default = strpos($ids, 'default') !== false)) {
if ($this->allow == 1 && !$not_default) {
$uri_path = __PS_BASE_URI__.$ids.($type ? '-'.$type : '').$theme.'/'.$name.'.jpg';
} else {
$uri_path = _THEME_PROD_DIR_.$ids.($type ? '-'.$type : '').$theme.'.jpg';
}
} else {
// if ids if of the form id_product-id_image, we want to extract the id_image part
$split_ids = explode('-', $ids);
$id_image = (isset($split_ids[1]) ? $split_ids[1] : $split_ids[0]);
$theme = ((Shop::isFeatureActive() && file_exists(_PS_PROD_IMG_DIR_.Image::getImgFolderStatic($id_image).$id_image.($type ? '-'.$type : '').'-'.(int)Context::getContext()->shop->id_theme.'.jpg')) ? '-'.Context::getContext()->shop->id_theme : '');
if ($this->allow == 1) {
$uri_path = __PS_BASE_URI__.$id_image.($type ? '-'.$type : '').$theme.'/'.$name.'.jpg';
} else {
$uri_path = _THEME_PROD_DIR_.Image::getImgFolderStatic($id_image).$id_image.($type ? '-'.$type : '').$theme.'.jpg';
}
}
return $this->protocol_content.Tools::getMediaServer($uri_path).$uri_path;
}
public function getMediaLink($filepath)
{
return $this->protocol_content.Tools::getMediaServer($filepath).$filepath;
}
PHP is not my strength, so I have no idea what to do :/
Also I found some other questions about Array to string notices, but it seemed to me like you can't solve them the same way...
Thanks in advance for any help!
This error is appearing because some of the variables in these two lines are supposed to be String but they are actually array.
You need to print all the variables used in these 2 lines using the var_dump() function of PHP, this will tell you which of the variables are actually an Array, but they are supposed to be a String as per your code.
On the basis of the output, you need to modify your code to fix the issue.

Calling PHP object attribute name from variable

There is a session variable called 'locale' with value: en.
$locale = session()->get('locale'); // value = 'en';
And there is an object $page with attributes: content_en, content_ru, content_de.
All I need is to echo $page->content_en or $page->content_ru or $page->content_de, but depending on locale.
echo $page->content_'.session()->get('locale').';
Here's a more complete solution that you can even run on phpfiddle.org
$page = new stdClass();
$page->content_en = 'Testcontent';
$page->content_de = 'Testinhalt';
$property = 'content_' . locale("en");
if(property_exists($page, $property)) {
// The property exists, print it!
echo $page->$property;
} else {
// Fallback to some default
}
function locale($loc)
{
return $loc;
}
You won't be able to access a property via a combined string.
The only option you have is to first put it in a string, and use that variable as a property access.
$property = 'content_' . session()->get('locale');
if( isset($page->$property) ) {
echo $page->$property;
}
Fabian's answer is more flexible and generally better. However, here's an alternative approach if you only accept specific values.
Using if
$locale = session()->get('locale'); // value = 'en';
if ($locale == "en") {
echo $page->content_en;
} elseif ($locale == "ru") {
echo $page->content_ru;
} elseif ($locale == "de") {
echo $page->content_de;
}
Using switch
$locale = session()->get('locale'); // value = 'en';
switch ($locale) {
case "en":
echo $page->content_en;
break;
case "ru":
echo $page->content_ru;
break;
case "de":
echo $page->content_de;
break;
}
This should do it:
echo $page->{'content_' . session()->get('locale')};

Unable to set session under switch/case condition

I am unable to set session for $_SESSION['next'] under switch/case condition, while $_SESSION['user_id'] works perfectly before the condition. The script run into each condition of switch/case condition and redirect without setting $_SESSION['next']. Is there any specific reason why it fails to work? How to solve this?
require_once ('../src/facebook.php');
require_once ('../src/fbconfig.php');
//Facebook Authentication part
$user_id = $facebook->getUser();
if ($user_id <> '0' && $user_id <> '') {
session_start();
$_SESSION['user_id'] = $user_id;
switch((isset($_GET['page']) ? $_GET['page'] : '')){
case 'abc';{
$_SESSION['next'] = 'AAA';
echo "<script>top.location.href = 'https://www.example.com/xxx/'</script>";
exit;}
case 'def';{
$_SESSION['next'] = 'BBB';
echo "<script>top.location.href = 'https://www.example.com/xxx/'</script>";
exit;}
case 'ghi';{
$_SESSION['next'] = 'CCC';
echo "<script>top.location.href = 'https://www.example.com/xxx/'</script>";
exit;}
default;{
echo "<script>top.location.href = 'https://www.example.com/xxx/'</script>";
exit;}
}
} else {
echo "<script>top.location.href = 'https://www.example.com/xxx/'</script>";
exit;
}
Your switch is all wrong. Read the manual and try this:
<?php
switch ((isset($_GET['page']) ? $_GET['page'] : '')){
case 'abc':
$_SESSION['next'] = 'AAA';
echo "<script>top.location.href = 'https://www.example.com/xxx/'</script>";
break;
case 'def':
$_SESSION['next'] = 'BBB';
echo "<script>top.location.href = 'https://www.example.com/xxx/'</script>";
break;
case 'ghi':
$_SESSION['next'] = 'CCC';
echo "<script>top.location.href = 'https://www.example.com/xxx/'</script>";
break;
default:
echo "<script>top.location.href = 'https://www.example.com/xxx/'</script>";
break;
}
You're using exit in your switch, which (unless you want your script to end at the switch) is a no-no. Instead, you have to use the break keyword.
You also use semicolons and curly braces for each case.
case 'ghi';{ ... }
NO! Proper usage is
case 'ghi':
.
.
.
break;
Update: I just noticed you use this line:
if ($user_id <> '0' && $user_id <> '') { ... }
What is <> doing in PHP code? The "standard" operator for "not equals" is != in PHP. Use it correctly or no one will want to use your code.
Second update: You never set $_SESSION['next'] in your default case. It's very likely that your switch is always going to the default case. This would cause the behavior you're experiencing.
I suggest:
if (($user_id != '0') && ($user_id != ''))
(parentheses, and the != operator)
and also a DRYer switch:
$page = array_key_exists('page', $_GET) ? $_GET['page'] : '';
switch ($page) {
case 'abc':
$next = 'AAA';
$loc = 'https://www.example.com/xxx/';
break;
case 'def':
$next = 'BBB';
$loc = 'https://www.example.com/yyy/';
break;
... // and so on
}
if (isset($next)) {
$_SESSION['next'] = $next;
// If it does not work, you have problems with your session ID, maybe?
}
// I find this syntax easier
print <<<SCRIPT
<script type="text/javascript">
top.location.href = '$loc';
</script>
SCRIPT;
exit();

Categories