Check if value is in array PHP (easy?) - php

I think I have a very easy question, but I am stuck anyway. I want to check if the value is in an array, and if it is, i want to change the variable value.
$admin_is_menu = "about";
$test = array();
$test = [
["Name" => "About","alias" => "about"],
["Name" => "Test", "alias" => "test"],
];
if(in_array($admin_is_menu, $test)){
$admin_is_menu = "true";
}
echo $admin_is_menu;
In the code above, it should output the echo "true", since "about" is in the array. But is unfortunally does not work.
What am I doing wrong?

Try array_column to get all array value.
$admin_is_menu = "about";
$test = array();
$test = [
["Name" => "About","alias" => "about"],
["Name" => "Test", "alias" => "test"],
];
if(in_array($admin_is_menu, array_column($test,'alias'))){
$admin_is_menu = "true";
}
echo $admin_is_menu;
DEMO

#cske pointed out in the comment how to do it. Here's a small explanation for that as well.
You should use array_column. In this case array_column($test, "alias") will return a new array:
array(2) {
[0]=>
string(5) "about"
[1]=>
string(4) "test"
}
Now, you check within it with in_array:
in_array($admin_is_menu, array_column($test,'alias'))
and this will return true

Related

Is there way to get value of CDATA and convert in json or array format in php?

Here is what it looks like after getting value from CDATA via simplexmlelement
$data = "{customertype=New, Telephone=09832354544, CITY=Henfield, LASTNAME=C, TicketNo=123456, FIRSTNAME=Alex, Id=10001273, testfield=123456, COMPANY=Camp1}"
I tried looking into solutions in google but i am not able to find one which would convert this set of strings to array.
I want this data to convert into array something like this
["customertype"] = ["New"]
["Telephone"] = ["09832354544"]
so and so forth or something similar as how array looks like.
Thanks in advance
Given your data string format, you may do as follows:
First of all, remove the brackets { }
Then explode the string using the , delimiter.
Now, you have array of strings containing for example customertype=New.
Next is the tricky part, the result string looks like a query, so we're gonna use
parse_str() to make an associative array:
The result will be something similar to this:
array:9 [▼
0 => array:1 [▼
"customertype" => "New"
]
1 => array:1 [▼
"Telephone" => "09832354544"
]
2 => array:1 [▼
"CITY" => "Henfield"
]
And here's the code:
$data = "{customertype=New, Telephone=09832354544, CITY=Henfield, LASTNAME=C, TicketNo=123456, FIRSTNAME=Alex, Id=10001273, testfield=123456, COMPANY=Camp1}";
$rippedData = str_replace(["{", "}"],"", $data);
$singleData= explode(",", $rippedData);
$finalArray = [];
foreach($singleData as $string){
parse_str($string, $output);
$finalArray[] = $output;
}
$data = "{customertype=New, Telephone=09832354544, CITY=Henfield, LASTNAME=C, TicketNo=123456, FIRSTNAME=Alex, Id=10001273, testfield=123456, COMPANY=Camp1}";
$stripped = str_replace(['{','}'], '', $data);
$explode = explode(', ', $stripped);
$output = [];
foreach ($explode as $value) {
$inner_explode = explode('=', $value);
$output[$inner_explode[0]] = $inner_explode[1];
}
var_dump($output);
Results in
array(9) {
["customertype"]=>
string(3) "New"
["Telephone"]=>
string(11) "09832354544"
["CITY"]=>
string(8) "Henfield"
["LASTNAME"]=>
string(1) "C"
["TicketNo"]=>
string(6) "123456"
["FIRSTNAME"]=>
string(4) "Alex"
["Id"]=>
string(8) "10001273"
["testfield"]=>
string(6) "123456"
["COMPANY"]=>
string(5) "Camp1"
}
This should work, though there's probably a better/cleaner way to code this.
$data = "{customertype=New, Telephone=09832354544, CITY=Henfield, LASTNAME=C, TicketNo=123456, FIRSTNAME=Alex, Id=10001273, testfield=123456, COMPANY=Camp1}";
// Replace squiggles
$replace_this = array("{","}");
$replace_data = str_replace($replace_this,"",$data);
// Explode and create array
$data_array = explode(',',$replace_data);
// Loop through the data_array
foreach($data_array as $value) {
// Explode the value on the equal sign
$explode_again = explode('=', $value);
// Create new array with correct indexes and values
$CDTA[trim($explode_again[0])] = $explode_again[1];
}
echo '<pre>' . var_export($CDTA, true) . '</pre>';
Result:
array (
'customertype' => 'New',
'Telephone' => '09832354544',
'CITY' => 'Henfield',
'LASTNAME' => 'C',
'TicketNo' => '123456',
'FIRSTNAME' => 'Alex',
'Id' => '10001273',
'testfield' => '123456',
'COMPANY' => 'Camp1',
)

unable to add key value pairs to complex object in php

I'm trying to create the follwing object in PHP:
$obj= {abc#gmail.com:[usr:130,fname:'Bob',lname:'thekid',news:0,wres:1,SWAGLeaders:0]}
ultimately $obj will have a number of email addresses each with its own array.
Here's what I have so far:
$obj = new stdClass();
$obj->{$user[0]['email']}=[];
where $user[0]['email] contains the email address.
my problem is I don't know how to add the elements to the array
You are on the right path if you really need an object.
$user[0]['email'] = 'test';
$obj = new stdClass();
$obj->{$user[0]['email']} = ['usr' => 130, 'fname' => 'Bob', 'lname' => 'thekid', 'news' => 0, 'wres' => 1, 'SWAGLeaders' => 0];
echo json_encode($obj);
Here's the output.
http://sandbox.onlinephpfunctions.com/code/035266a29425193251b74f0757bdd0a3580a31bf
But, I personally don't see a need for an object, I'd go with an array with a bit simpler syntax.
$user[0]['email'] = 'test';
$obj[$user[0]['email']] = ['usr' => 130, 'fname' => 'Bob', 'lname' => 'thekid', 'news' => 0, 'wres' => 1, 'SWAGLeaders' => 0];
echo json_encode($obj);
http://sandbox.onlinephpfunctions.com/code/13c1b5308907588afc8721c1354f113c641f8788
The same way you assigned the array to the object in the first place.
$user[0]['email'] = "abc#gmail.com";
$obj = new stdClass;
$obj->{$user[0]['email']} = [];
$obj->{$user[0]['email']}[] = "Element 1";
$obj->{$user[0]['email']}[] = "Element 2";
$obj->{$user[0]['email']}[] = "Element 3";
var_dump($obj);
object(stdClass)#1 (1) {
["abc#gmail.com"]=>
array(3) {
[0]=>
string(9) "Element 1"
[1]=>
string(9) "Element 2"
[2]=>
string(9) "Element 3"
}
}

Dynamically accessing multidimensional array value

I'm trying to find (or create) a function. I have a multidimensional array:
$data_arr = [
"a" => [
"aa" => "abfoo",
"ab" => [
"aba" => "abafoo",
"abb" => "abbfoo",
"abc" => "abcfoo"
],
"ac" => "acfoo"
],
"b" => [
"ba" => "bafoo",
"bb" => "bbfoo",
"bc" => "bcfoo"
],
"c" => [
"ca" => "cafoo",
"cb" => "cbfoo",
"cc" => "ccfoo"
]
];
And I want to access a value using a single-dimentional array, like this:
$data_arr_call = ["a", "ab", "abc"];
someFunction( $data_arr, $data_arr_call ); // should return "abcfoo"
This seems like there's probably already a function for this type of thing, I just don't know what to search for.
Try this
function flatCall($data_arr, $data_arr_call){
$current = $data_arr;
foreach($data_arr_call as $key){
$current = $current[$key];
}
return $current;
}
OP's Explanation:
The $current variable gets iteratively built up, like so:
flatCall($data_arr, ['a','ab','abc']);
1st iteration: $current = $data_arr['a'];
2nd iteration: $current = $data_arr['a']['ab'];
3rd iteration: $current = $data_arr['a']['ab']['abc'];
You could also do if ( isset($current) ) ... in each iteration to provide an error-check.
You can use this function that avoids the copy of the whole array (using references), is able to return a NULL value (using array_key_exists instead of isset), and that throws an exception when the path doesn't exist:
function getItem(&$array, $path) {
$target = &$array;
foreach($path as $key) {
if (array_key_exists($key, $target))
$target = &$target[$key];
else throw new Exception('Undefined path: ["' . implode('","', $path) . '"]');
}
return $target;
}
demo:
$data = [
"a" => [
"aa" => "abfoo",
"ab" => [
"aba" => "abafoo",
"abb" => NULL,
"abc" => false
]
]
];
var_dump(getItem($data, ['a', 'ab', 'aba']));
# string(6) "abafoo"
var_dump(getItem($data, ['a', 'ab', 'abb']));
# NULL
var_dump(getItem($data, ['a', 'ab', 'abc']));
# bool(false)
try {
getItem($data, ['a', 'ab', 'abe']);
} catch(Exception $e) {
echo $e->getMessage();
}
# Undefined path: ["a","ab","abe"]
Note that this function can be improved, for example you can test if the parameters are arrays.
Wanted to post an even more elegant solution: array_reduce
$data_arr = [
"a" => [
...
"ab" => [
...
"abc" => "abcfoo"
],
...
],
...
];
$result = array_reduce(["a", "ab", "abc"], function($a, $b) {
return $a[$b];
}, $data_arr);
// returns "abcfoo"
I've been using Javascript's Array.reduce() a lot lately in updating some legacy code to ES6:
JS:
const data_obj = {...};
let result = ['a','ab','abc'].reduce((a, b) => a[b], data_obj);
You need a function like this:
function getValue($data_arr, $data_arr_call) {
foreach ($data_arr_call as $index) {
if (isset($data_arr[$index])) {
$data_arr = $data_arr[$index];
} else {
return false;
}
}
return $data_arr;
}
And use it like this:
$data_arr = [
"a" => [
"ab" => [
"abc" => "abbfoo",
],
],
];
$data_arr_call = ["a", "ab", "abc"];
$value = getValue($data_arr, $data_arr_call);
if ($value) {
// do your stuff
}

How to combine a constant string to all values of array?

I have a array like this:
$arr = array(
"0" => "Jack",
"1" => "Peter",
"2" => "ali"
);
Now I want to add My name is: to the first of all those values...! How can I do that?
Note: I can do that using a loop, and fetch all values, and combine them using . and push them into array again. But I want to know is there any function for doing that? Or any better solution?
So I want this output:
$newarr = array(
"0" => "My name is: Jack",
"1" => "My name is: Peter",
"2" => "My name is: ali"
);
Use array_walk as below :
<?php
$arr = array (
"0" => "Jack",
"2" => "Peter",
"3" => "ali"
);
array_walk($arr, function(&$item) {
$item = 'My Name is : '.$item;
});
print_r($arr);
?>
or you can use array_map as below
<?php
$arr = array (
"0" => "Jack",
"2" => "Peter",
"3" => "ali"
);
$arr = array_map(function($val) {
return "My name is : ".$val;
} , $arr);
print_r($arr);
?>
Use array_walk. It Applies a user supplied function to every member of an array. In your case, we are going to concatenate your string. See the example below.
<?php
$arr = array(
"0" => "Jack",
"2" => "Peter",
"3" => "ali"
);
array_walk($arr, function(&$name) {
$name = 'My Name is : ' . $name;
});
echo '<pre>';
print_r($arr);
echo '</pre>';
?>
you can use array_map function, see code
$arr = array (
"0" => "Jack",
"2" => "Peter",
"3" => "ali"
);
function changeName($name)
{
return('My name is: '.$name);
}
$b = array_map("changeName", $arr);
print_r($b);
A better solution is to only output the "My name is:" when needed. You may use array_map or a foreach loop.
If you keep the array with only names you can reuse it more easily in the future.
Consider the following cases:
sorting the names
providing a different string for the same array later in the code
using the names without the string later in the code
Also, you don't have to explicitly set the keys in this case, you could use notation like this:
$names = [ "Jim", "Dave"];
Use a for loop which uses the original array elements:
$arr = array (
"0" => "Jack",
"1" => "Peter",
"2" => "ali"
);
for ($i=0;$i<count($arr);$i++)
$arr[$i] = "My name is: " . $arr[$i];
print_r($arr);

Passing/Returning references to object + changing object is not working

I am using an answer from How to get random value out of an array to write a function that returns a random item from the array. I modified it to pass by reference and return a reference.
Unfortunately, it doesn't appear to work. Any modifications to the returned object do not persist. What am I doing wrong?
I'm on PHP 5.4 if that makes a difference (Don't ask).
function &random_value(&$array, $default=null)
{
$k = mt_rand(0, count($array) - 1);
$return = isset($array[$k])? $array[$k]: $default;
return $return;
}
Usage...
$companies = array();
$companies[] = array("name" => "Acme Co", "employees"=> array( "John", "Jane" ));
$companies[] = array("name" => "Inotech", "employees"=> array( "Bill", "Michael" ));
$x = &random_value($companies);
$x["employees"][] = "Donald";
var_dump($companies);
Output...
array(2) {
[0] =>
array(2) {
'name' =>
string(7) "Acme Co"
'employees' =>
array(2) {
[0] =>
string(4) "John"
[1] =>
string(4) "Jane"
}
}
[1] =>
array(2) {
'name' =>
string(7) "Inotech"
'employees' =>
array(2) {
[0] =>
string(4) "Bill"
[1] =>
string(7) "Michael"
}
}
}
I even copied and pasted the examples from the documentation and none of those worked either. They all output null.
The ternary operator creates an implicit copy, which breaks the reference chain. Use an explicit if... else:
function &random_value(&$array, $default=null)
{
$k = mt_rand(0, count($array) - 1);
if (isset($array[$k])) {
return $array[$k];
} else {
return $default;
}
}
As to why, the docs now state:
Note: Please note that the ternary operator is an expression, and that it doesn't evaluate to a variable, but to the result of an expression. This is important to know if you want to return a variable by reference. The statement return $var == 42 ? $a : $b; in a return-by-reference function will therefore not work and a warning is issued in later PHP versions.
See also this bug where the ternary operator actually returns by reference in a foreach context, when it shouldn't.
I'm having trouble wrapping my head around a better function aspect than #bishop as I have just consumed an enormous lunch, however this works:
$x =& $companies[array_rand($companies)];
$x["employees"][] = "Donald";
var_dump($companies);

Categories