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);
Related
I've just come across a problem, which apparently looks simple, but I can't find a solution. I have the following array in PHP:
[
"name" => "user"
0 => "created_at"
"email" => "mail"
]
And I need to get an array like this:
[
"name"
"created_at"
"email"
]
As you can see, I only need to obtain the original keys from the array, but in case a value from the original array does not have an associated value, then return the value instead of the key.
I have tried several ways using the following methods:
array_flip()
array_keys()
array_values()
I would appreciate in advance anyone who could help me.
Loop through the array and add the desired values to your new array:
$a = [
"name" => "user",
0 => "created_at",
"email" => "mail",
];
$b = [];
foreach ( $a as $k => $v ) {
$b[] = ( $k ? $k : $v );
}
print_r($b);
/*
Array
(
[0] => name
[1] => created_at
[2] => email
)
*/
For a more sophisticated determination of which key(s) to keep, replace the first $k in the ternary expression with a function that tests $k for validity:
$b[] = ( test($k) ? $k : $v );
// ...
function test($k) {
return ! is_number($k); // For example
}
is just a simple foreach
<?php
$test=
[
"name" => "user"
,0 => "created_at"
,"email" => "mail"
];
$res=[];
foreach(array_keys($test) as $ch){
(is_numeric($ch) and ($res[]=$test[$ch]) )or ($res[]=$ch);
}
var_dump($res);
?>
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
Im trying to build a json array in php with this structure:
[{"id":"name last name",
"id":"name last name",
"id":"name last name"
}]
where the id key is always a different number, not only id string
Im trying to do this:
for ($i = 0; $i < count($array); $i++){
//$namesArray[] = array($array[$i]["id"] =>$array[$i]["name"].
// " ".$array[$i]["last"]." ".$array[$i]["name"]);
$namesArray[] = array_fill_keys(
$array[$i]["id"],
$array[$i]["name"]." ".
$array[$i]["last"]." ".
$array[$i]["name"]
);
}
echo json_encode($namesArray);
With the commented lines I get something like this:
[{"id":"name last name"},
{"id":"name last name"}
]
But I dont want that, I want all keys and values in a single array.
Thanks.
Keep your code clean
$array = [];
$array[] = ['id'=>3 , 'name'=>'H', 'last'=>'bensiali' ];
$array[] = ['id'=>4 , 'name'=>'Simon', 'last'=>'Says' ];
$array[] = ['id'=>5 , 'name'=>'Mohammed', 'last'=>'Ali' ];
$val = [];
foreach ($array as $key => $value) {
$val[$value['id']] = sprintf("%s %s" , $value['name'] , $value['last']);
}
echo json_encode($val);
And output will be:
{"3":"H bensiali","4":"Simon Says","5":"Mohammed Ali"}
Here is how you can do it:
// sample data
$array = array(
array("id" => 1, "name" => "James", "last" => "Last"),
array("id" => 2, "name" => "Micheal", "last" => "Jackson"),
);
// create empty object (associative array)
$obj = (object) array();
// add key/value pairs to that object
foreach ($array as $row) {
$obj->$row["id"] = $row["name"] . " " . $row["last"];
}
// wrap object in a single-element array
$result = array($obj);
// output to JSON string
echo json_encode($result, JSON_PRETTY_PRINT);
Output:
[
{
"1": "James Last",
"2": "Micheal Jackson"
}
]
You can use functional approach to fill desired array with array_reduce:
$array = [
['id' => 1, 'name' => 'name1', 'last' => 'last1'],
['id' => 2, 'name' => 'name2', 'last' => 'last2'],
['id' => 3, 'name' => 'name3', 'last' => 'last3'],
];
$newArray = array_reduce($array, function($carry, $item) {
$carry[$item['id']] = $item["name"]." ".
$item["last"]." ".
$item["name"];
return $carry;
});
var_dump($newArray);
And output will be:
array(3) {
[1]=>
string(17) "name1 last1 name1"
[2]=>
string(17) "name2 last2 name2"
[3]=>
string(17) "name3 last3 name3"
}
Ive got an associative array like this
$array = array (
"name" => "bob",
"age" => "22",
"sex" => "male"
)
and to return this data to the screen im using
echo $array['name'] . $array['age'] . $array['sex'];
is there a cleaner way to do this ?
For better reading use the following function:
function print_array($input) {
return '<pre>'.$print_r($input, true).'</pre>';
}
for working with it use:
echo print_array($array);
This prints out a pre formatted array, where you dont have to look in the source to view it propperly
Also you can use this if you just don't want to print elements of array and do some other stuff.
foreach($array as $item){
echo $item;
}
If it's just for debugging you could use
print_r($array);
or
var_dump($array);
Also you could look at vsprintf which would allow you to format a string with all of the elements of your array.
Try:
$array = array (
"name" => "bob",
"age" => "22",
"sex" => "male"
);
foreach($array as $key=>$value){
echo $key . ' = ' . $value . ' - ';
}
you can try this:
$array = array (
"name" => "bob",
"age" => "22",
"sex" => "male"
);
function print_array($arr){
$keys= array_keys($arr);
foreach ($keys as $key) {
echo $arr[$key].' ';
}
}
print_array($array);
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Search and replace inside an associative array
I think this may have been asked before. But I just want a simple solution.
I have an array like this:
Array ( "name" => "Krish",
"age" => "27",
"COD" => ""
)
I want to replace "" with "0"
Its a multidimentional array. The return value should be array too.
Edit: I tried preg_replace and str_replace. For some reason, these did not work for me.
$array = array(
"name" => "Krish",
"age" => "27",
"COD" => ""
);
you may loop the array and repalce what you want
foreach($array as $key => $value)
{
if($value == "") $array[$key] = 0;
}
Note:
if you know what key is it you can do it like this
$array['cod'] = 0;
$entry = array("name" => "Krish",
"age" => "27",
"COD" => "");
$arr = array_filter($entry, 'valcheck');
print_r($entry); //ORIGINAL ARRAY
print_r($arr); //MODIFIED ARRAY
function valcheck($var)
{
if($var === "")
return 0;
else
return $var;
}
if your array is $array:
$array['COD'] = "0";
<?php
$arr=array(
"name" => "Krish",
"age" => "27",
"COD" => ""
);
print_r(array_map(function($i){return (''===$i)?0:$i;},$arr));
?>