I need to check if a key exists and return its value if it does.
Key can be an array with subkeys or endkey with a value.
$_SESSION['mainKey']['testkey'] = 'value';
var_dump(doesKeyExist('testkey'));
function doesKeyExist($where) {
$parts = explode('/',$where);
$str = '';
for($i = 0,$len = count($parts);$i<$len;$i++) {
$str .= '[\''. $parts[$i] .'\']';
}
$keycheck = '$_SESSION[\'mainKey\']' . $str;
if (isset(${$keycheck})) {
return ${$keycheck};
}
// isset($keycheck) = true, as its non-empty. actual content is not checked
// isset(${$keycheck}) = false, but should be true. ${$var} forces a evaluate content
// isset($_SESSION['mainKey']['testkey']) = true
}
Using PHP 5.3.3.
Instead of building the string, just check if the key exists within your loop.
For instance:
function doesKeyExist($where) {
$parts = explode('/',$where);
$currentPart = $_SESSION['mainKey'];
foreach($parts as $part) {
if (!isset($currentPart[$part])) {
return false;
}
$currentPart = $currentPart[$part];
}
return true;
}
function getByKeys($keys, $array) {
$value = $array;
foreach (explode('/', $keys) as $key) {
if (isset($value[$key])) {
$value = $value[$key];
} else {
return null;
}
}
return $value;
}
Perhaps I'm misunderstanding the question, but this would appear to be the simplest way of doing it:
function getKey($arr, $key) {
if (array_key_exists($key, $arr)) {
return $arr[$key];
} else {
return false;
}
}
$value = getKey($_SESSION['mainKey'], 'testkey');
You should use $$keycheck, not ${$keycheck}.
The last notation is only if you use the variable inside a string (e.g. "${$keycheck}")
See http://php.net/manual/en/language.variables.variable.php for more details about variable variables
You might want to use the eval() php function for this.
function doesKeyExist($where) {
$parts = explode('/',$where);
$str = '';
for($i = 0,$len = count($parts);$i<$len;$i++) {
$str .= '["'. $parts[$i] .'"]';
}
eval('$keycheck = $_SESSION["mainKey"]' . $str . ';');
if (isset($keycheck)) {
return $keycheck;
}
}
HTH
Related
$printArr = recursive($newArray); //calls recursive function
$data = [];
var_dump($data);
var_dump($printArr);
function recursive($array, $level = 0)
{
$searchingValue = 'tableName';
foreach($array as $key => $value)
{
//If $value is an array.
if(is_array($value))
{
recursive($value, $level + 1);
}
else
{
//It is not an array, so print it out.
if($key == $searchingValue)
{
echo "[".$key . "] => " . $value, '<br>';
$data[] = $value;
}
}
}
}
So I have this function and I am trying to save $value value into $data[] array. But it always returns it empty and I don't know why I can't get $value saved outside the function.
If i echo $value I get what i need but like I've mentioned the variables doesn't get saved in this case - table names.
You need to pass the $data to your recursive function. Also you need to return the $data.
Try this code :
function recursive($array, $level = 0, $data =[])
{
$searchingValue = 'tableName';
foreach($array as $key => $value)
{
//If $value is an array.
if(is_array($value))
{
recursive($value, $level + 1 , $data);
}
else
{
//It is not an array, so print it out.
if($key == $searchingValue)
{
echo "[".$key . "] => " . $value, '<br>';
$data[] = $value;
}
}
}
return $data;
}
You can't access variable $data, which is outside the function, from the function. You need to pass it by reference or return it. Small example
<?php
$a = 1;
// Your case
function b() {
$a = 4;
return true;
}
// Passing by reference
function c(&$d) {
$d = 5;
return true;
}
// Using return
function d($d) {
$d = 6;
return $d;
}
b();
var_dump($a);
c($a);
var_dump($a);
$a = d($a);
var_dump($a);
https://3v4l.org/UXFdR
I just want to know how to replace a certain index character with an array constantly like how PDO works in PHP? Here is my code;
The the code
private $string;
public function __construct($string = null) {
if ($string !== null) {
$this->string = $string;
} else {
$this->string = '';
}
}
public function getString() {
return $this->string;
}
public function replaceWith($index, $array = array()) {
$lastArrayPoint = 0;
$i = 0;
while ($i < sizeof($this->string)) {
if (substr($this->string, $i, $i + 1) == $index) {
$newString[$i] = $array[$lastArrayPoint];
$i = $i . sizeof($array[$lastArrayPoint]);
$lastArrayPoint++;
} else {
$newString[$i] = $this->string[$i];
}
$i++;
}
return $this;
}
and the executing code
$string = new CustomString("if ? == true then do ?");
$string->replaceWith('?', array("mango", "print MANGO"));
echo '<li><pre>' . $string->getString() . '</pre></li>';
Thank you for the help I hope I will recieve.
$string = "if %s == true then do %s. Escaping %% is out of the box.";
$string = vsprintf($string, array("mango", "print MANGO"));
echo "<li><pre>$string</pre></li>";
str_replace has an optional count parameter, so you can make it replace one occurrance at a time. You can just loop through the array, and replace the next question mark for element N.
$string = "if %s == true then do %s";
$params = array("mango", "print MANGO");
foreach ($params as $param)
$string = str_replace('?', $param, $string, 1);
Thanks for the help guys but they did not work the way I wanted it to work. I have found a way to get it too work. Here is the code
public function replaceWith($index, $array = array()) {
$arrayPoint = 0;
$i = 0;
$newString = "";
while ($i < strlen($this->string)) {
if (substr($this->string, $i, 1) === $index) {
$newString .= $array[$arrayPoint];
$arrayPoint++;
} else {
$newString .= substr($this->string, $i, 1);
}
$i++;
}
$this->string = $newString;
return $this;
}
if anyone has a better way then you can tell me but for now this works.
I'm trying to validate a string to an array of numbers. If the string only contains numbers then the function should validate, but in_array isn't working, any suggestions?
$list = array(0,1,2,3,4,5,6,7,8,9);
$word = 'word';
$split = str_split($word);
foreach ($split as $s) {
if (!in_array($s, $list)) {
print 'asdf';
}
}
here is the class:
class Validate_Rule_Whitelist {
public function validate($data, $whitelist) {
if (!Validate_Rule_Type_Character::getInstance()->validate($data)) {
return false;
}
$invalids = array();
$data_array = str_split($data);
foreach ($data_array as $k => $char) {
if (!in_array($char, $whitelist)) {
$invalids[] = 'Invalid character at position '.$k.'.';
}
}
if (!empty($invalids)) {
$message = implode(' ', $invalids);
return $message;
}
return true;
}
}
in_array comparison with loosely typed values is somewhat strange. What would work in your case is:
$list = array('0','1','2','3','4','5','6','7','8','9');
$word = 'word';
$split = str_split($word);
foreach ($split as $s) {
if (!in_array($s, $list, true)) {
print 'asdf';
}
}
This compares strings with strings and results in no surprises.
But, as noted in the comments already, this is quite wrong way to do things and it is much better to use filter_var() or regular expressions** to achieve what you're trying.
it's ugly as sin but it works, no elegant solution here, just a double loop, if you see any problems please let me know
$match = array();
foreach ($data_array as $k => $char) {
foreach ($whitelist as $w) {
if (!isset($match[$k])) {
if ($char === $w) {
$match[$k] = true;
}
}
}
if (!isset($match[$k]) || $match[$k] !== true) {
$invalids[$k] = 'Invalid character at position '.$k.'.';
}
}
Something along the lines of this should work:
<?php
$validate_me = '123xyz';
if(preg_match("/[^0-9]/", $validate_me, $matches))
print "non-digit detected";
?>
update: add the $type = gettype ... settype($char, $type) to allow === to function correctly when checking for integers
foreach ($data_array as $k => $char) {
foreach ($whitelist as $w) {
if (!isset($match[$k])) {
$type = gettype($w);
if (gettype($char) !== $type) {
settype($char, $type);
}
if ($char === $w) {
$match[$k] = true;
}
}
}
...
Given a multidimensional array or dictionary $array.
And assuming that $array['foo']['bar']['baz'] = 'something';
Is there a way other than via an eval statement for me use the multi-dimentional index foo/bar/baz? (The use case is in creating the index dynamically i.e. The function does not know what /foo/bar/baz/ is).
The only way I could figure to do this was:
$item = testGetIndex($array, "'foo']['bar']['baz'");
function testGetIndex($array, $index) {
eval('$item = $array[' . $index . '];');
return $item;
}
Note:
I should mention that I do not want to search this array. This is a weird use case. I am being passed a very large multi dimensional array and it's ugly to have to use constructs like..
$array[foo][bar]..[baz] to make modifications to the array.
Blatently reusing my answer here:
function recurseKeys(array $keys,array $array){
$key = array_shift($keys);
if(!isset($array[$key])) return null;
return empty($keys) ?
$array[$key]:
recurseKeys($keys,$array[$key];
}
$values = recurseKeys(explode('/','foo/bar/baz'),$yourArray);
edit: as Jack pointed out, recursion is not needed:
function findByKey(array $keys,array $array){
while(!is_null($key = array_shift($keys))){
if(!isset($array[$key])) return null;
$array = $array[$key];
}
return $array;
}
$values = findByKey(explode('/','foo/bar/baz'),$yourArray);
To modify an array using a path:
function setPath(&$root, $path, $value)
{
$paths = explode('/', $path);
$current = &$root;
foreach ($paths as $path) {
if (isset($current[$path])) {
$current = &$current[$path];
} else {
return null;
}
}
return $current = $value;
}
$path = 'foo/bar/baz';
$root = array('foo' => array('bar' => array('baz' => 'something')));
setPath($root, $path, '123');
You can tweak the function to just return a reference to the element you wish to change:
function &getPath(&$root, $path)
{
$paths = explode('/', $path);
$current = &$root;
foreach ($paths as $path) {
if (isset($current[$path])) {
$current = &$current[$path];
} else {
return null;
}
}
return $current;
}
$x = &getPath($root, $path);
$x = 456; // $root['foo']['bar']['baz'] == 456
A simple loop can make it, like:
function get(array $array, $keys) {
$val = $array;
foreach (explode('/', $keys) as $part) {
if (!isset($val[$part])) {
return null;
}
$val = $val[$part];
}
return $val;
}
$array['foo']['bar']['baz'] = 'something';
echo get($array, 'foo/bar/baz');
http://ideone.com/vcRvXW
Edit:
For modification, just use references:
function set(array &$array, $keys, $value) {
$val = &$array;
foreach (explode('/', $keys) as $part) {
if (!isset($val[$part])) {
$val[$part] = array();
}
$val = &$val[$part];
}
$val = $value;
}
http://ideone.com/WUNhF6
Is it possible to do something like this in PHP?
$index1 = "[0][1][2]";
$index2 = "['cat']['cow']['dog']";
// I want this to be $myArray[0][1][2]
$myArray{$index1} = 'stuff';
// I want this to be $myArray['cat']['cow']['dog']
$myArray{$index2} = 'morestuff';
I've searched for a solution, but I don't think I know the keywords involved in figuring this out.
eval('$myArray[0][1][2] = "stuff";');
eval('$myArray'.$index1.' = "stuff";');
But be careful when using eval and user input as it is vulnerable to code injection attacks.
Not directly. $myArray[$index] would evaluate to $myArray['[0][1][2]']. You would probably have to separate each dimension or write a little function to interpret the string:
function strIndexArray($arr, $indices, $offset = 0) {
$lb = strpos($indices, '[', $offset);
if ($lb === -1) {
return $arr[$indices];
}
else {
$rb = strpos($indices,']', $lb);
$index = substr($indices, $lb, $rb - $lb);
return strIndexArray($arr[$index], substr($indices, $rb+1));
}
}
You can probably find some regular expression to more easily extract the indices which would lead to something like:
$indices = /*regex*/;
$value = '';
foreach($indices as $index) {
$value = $array[$index];
}
To set a value in the array the following function could be used:
function setValue(&$arr, $indices, $value) {
$lb = strpos($indices, '[');
if ($lb === -1) {
$arr = $value;
}
else {
$rb = strpos($indices, ']', $lb);
$index = substr($indices, $lb, $rb);
setValue($arr[$index], substr($indices, $lb, $rb+1), $value);
}
}
Note: I made above code in the answer editor so it may contain a typo or two ; )
$index1 = "[0][1][2]";
$index2 = "['cat']['cow']['dog']";
function myArrayFunc(&$myArray,$myIndex,$myData) {
$myIndex = explode('][',trim($myIndex,'[]'));
$m = &$myArray;
foreach($myIndex as $myNode) {
$myNode = trim($myNode,"'");
$m[$myNode] = NULL;
$m = &$m[$myNode];
}
$m = $myData;
}
// I want this to be $myArray[0][1][2]
myArrayFunc($myArray,$index1,'stuff');
// I want this to be $myArray['cat']['cow']['dog']
myArrayFunc($myArray,$index2,'morestuff');
var_dump($myArray);
There's always the evil eval:
eval('$myArray' . $index1 . ' = "stuff";');
You can use two anonymous functions for this.
$getThatValue = function($array){ return $array[0][1][2]; };
$setThatValue = function(&$array, $val){ $array[0][1][2] = $val; };
$setThatValue($myArray, 'whatever');
$myValue = $getThatValue($myArray);